'Why can't we use base class reference to a derived class object if inheriting privately?
It might be a stupid question, but I'm wondering. If we're inheriting publicly - public methods of base class are becoming public methods of the derived class. If we're inheriting privately - public methods of base class are becoming private methods of derived class. So:
If we're making two classes, like:
Testing1 (which inherits publicly) and Testing2 (which inherits privately):
class Testing1 : public std::string
{
private:
std::string a;
public:
Testing1(std::string str = "Null") : a(str) {};
};
class Testing2 : private std::string
{
public:
Testing2(std::string str = "Null") : std::string(str) {}
};
Why is it that we can make a base class reference in the class where we're inheriting publicly:
Testing1 a;
std::string* ptr1 = &a;
std::string& ref1 = a;
But we can't use the base class reference to a derived class in the class where it's inherited privately?
/* Can't do this */
Testing2 b;
std::string* ptr2 = &b; // -> error
std::string& ref2 = b; // -> error
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
