C++ has 4 types of inheritance. Let's start with public inheritance:
class A {
public:
void one() {}
protected:
void two() {}
private:
void three() {}
};
class B : public A {};
Public inheritance implies that class B inherits all public and protected methods from class A as is. This is what signature of class B looks like now:
class B : public A
{
public:
void one() {}
protected:
void two() {}
};
Let's move on and take a look at protected inheritance as well:
class B : protected A
{
protected:
void one() {}
void two() {}
};
As you can see the difference between the two is that all public methods of class A become protected in class B. Now, guess what happens when you use private inheritance? This is what happens:
class B : private A
{
private:
void one() {}
void two() {}
};
All public and protected methods inherited from A become private. Ok, I said there are 4, the fourth one is so-called virtual inheritance which allows you to literally share your base class when, for instance to fight famous diamond problem. Let's create some kinda diamond for clarity:
class Top
{
public:
Top()
{
std::cout << "Hello, I am the top." << std::endl;
}
void topMethod() {}
};
class Left : public Top
{
public:
void leftMethod()
{
topMethod();
}
};
class Right : public Top
{
public:
void rightMethod()
{
topMethod();
}
};
class Bottom : public Left, public Right
{
public:
void bottomMethod()
{
leftMethod();
rightMethod();
}
};
Despite the fact that there will be two Top classes in our hierarchy, this will compile and run like it's no problem. Please run it and you'll see that Top constructor gets called twice. If such a behavior bothers you, you can get rid of the second Top class using virtual inheritance:
class Top
{
public:
Top()
{
std::cout << "Hello, I am the top." << std::endl;
}
void topMethod() {}
};
class Left : public virtual Top
{
public:
void leftMethod()
{
topMethod();
}
};
class Right : public virtual Top
{
public:
void rightMethod()
{
topMethod();
}
};
class Bottom : public Left, public Right
{
public:
void bottomMethod()
{
leftMethod();
rightMethod();
}
};
Now, run it again to make sure we have only one Top.
No comments:
Post a Comment