So i was having this question "What members of a class can be accessed from a class derived from it?"
I thought that it depends on how we use this base class (
public
,
private
,
protected
)
Theoretically i read that :
If a base class is
private
than
protected
and
private
members can be used only by derived classes.
If base class is
protected
than same thing except that 1st derived class can be used further as base class to other classes.
If base class is
public
than
public
member names can be used by all functions. At one place i read that this basically means that derived class basically becomes its base class and u can use derived class in places where base class argument is necessary. But on the other place i read that u still cant access base's
private
parts.
So i tried to check out what can i actually access in every possible case in practice and turned out that i can't even access protected part constructor from my Base class (class D_public : public Base). I even tried typing
using Base::Base;
as B.Stroustrup did in his book but still nothing.
Maybe i have to write brand new constructor for all the derived classes? If that's so what's the point of "taking" members from base class if u have to redefine them all over again anyway?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
#include <iostream>
using namespace std;
class Base{
public:
int get_x(){ return x; }
protected:
Base(int num) : x{ num }{}
virtual void set_x(int num){ x = num; }
private:
int x;
};
class D_public : public Base{
};
class D_protected : protected Base{
};
class D_private : private Base{
};
int main(){
D_public pub{ 5 };
system("pause");
}
|
Compiler error :
Error 1 error C2440: 'initializing' : cannot convert from 'initializer-list' to 'D_public'
|