The point of interfaces
Whats the point of making interfaces in C++?
For example
class CInterface
{
public:
virtual function(void) = 0;
};
And then implement it with some derived class.
What is the point of this when you could just use the implementation class and skip the interface class totally?
class CInterface
{
public:
virtual void function()=0;
};
class Shotgun : public CInterface
{
public:
virtual void function() {}
};
class Gun : public CInterface
{
public:
virtual void function() { i = 5;}
private:
int i;
};
//
void dostuff(CInterface *b)
{
b->function();
}
//
CInterface *a = new Shotgun();
CInterface *b = new Gun();
dostuff(a);
dostuff(b);
I hope this clears some things up. Very useful in lists''n stuff.
{
public:
virtual void function()=0;
};
class Shotgun : public CInterface
{
public:
virtual void function() {}
};
class Gun : public CInterface
{
public:
virtual void function() { i = 5;}
private:
int i;
};
//
void dostuff(CInterface *b)
{
b->function();
}
//
CInterface *a = new Shotgun();
CInterface *b = new Gun();
dostuff(a);
dostuff(b);
I hope this clears some things up. Very useful in lists''n stuff.
A polar bear is a rectangular bear after a coordinate transform.
July 25, 2000 08:17 PM
One of the major reasons to use interfaces is because it forces better code seperation. If you make some minor change to the implementation class (but the interface is still valid) then you don''t have to rebuild your entire program because presumably only the implementation can see it and not any users of the interface.
Closely related to this is that you have fewer dependencies. If the implementation of CInterface uses CFoo and CBar and the user can see the implementation class definition then they have to do all the necessary includes to get CFoo and CBar also. With a seperate interface class they don''t.
Yet another reason is that if you can see the actual implementation you might be tempted to cheat and not use the interface properly because you have details about how it works.
-Mike
Closely related to this is that you have fewer dependencies. If the implementation of CInterface uses CFoo and CBar and the user can see the implementation class definition then they have to do all the necessary includes to get CFoo and CBar also. With a seperate interface class they don''t.
Yet another reason is that if you can see the actual implementation you might be tempted to cheat and not use the interface properly because you have details about how it works.
-Mike
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement
Recommended Tutorials
Advertisement