0

Forgive me if the question is a duplication....I was not able to get a satisfying answer, so posting the questing in my way....

Consider the sample code

class Base {
protected:
     Base() {}
};
class Derived:public Base {
public:
     void func() {
        Base obj;
     }
};

The above code will thow a compilation error saying the constructor of Base is protected. But if I create an Object of Derived class in main the constructor of Base class is getting called( I know its called internally by the Derived class constructor), which means Base class constructor can be called from a Derived class function. Then why we are not able to create an Base class object within a derived class function...?

And one more thing....is there any other way to instantiate an object of a class whose constructor in protected, other than inside a method of the same class(as we do while creating Singleton )...?

2 Answers2

2

The access type protected only grants access to "your own" members inherited from the parent class. Unlike e.g. Java, C++ has quite a strict interpretation of that concept, allowing you to only access inherited members of the same instance.

By using the constructor you are technically trying to access non-public implementation details of another instance, which is forbidden.

Wormbo
  • 4,978
  • 2
  • 21
  • 41
  • So is there any other way to instantiate an object of a class whose constructor in protected, other than from a static public method of the Base class(ie. Creating Singleton ) – Jose John Thottungal Jan 02 '15 at 09:19
2

A mistake is to think that you are validly trying to access a protected base class member. You're not doing that. You're trying to create an instance of a class with a constructor marked as protected. By marking a constructor as protected, you are specifically forbidding construction of an instance of that class. That is only possible inside a derived class's constructor. And that is why you found it to work in the main() program.

The only way to create an instance of Base without removing the protected specifier, is to create an instance of Derived which "is a" instance of Base. Or create another derived class that doesn't add any overridden behaviour to `Base'.

acraig5075
  • 10,588
  • 3
  • 31
  • 50