0
votes

Base class function and derived class function having the same signature but inherited as protected .In main i have assigned derived class object to a base class pointer and i am trying to access the function .It causes error. Is it because of Protected?

 class base{

    public:
    void test(){
    cout<<"test in base\n";

    }
    };
    class derived:protected base{

    public:

     void test(){
    cout<<"test in derived\n";

    }

    };



    int main(){

    base *ptr;
    derived obj;
    ptr=&obj;
    ptr->test();

    return 0;
    }

error:

In function 'int main()':

error: 'base' is an inaccessible base of 'derived'

     ptr=&obj;

          ^~~
2
Maybe, but you've not posted any code so can't say for sure.UKMonkey
Maybe you are missing a ; on line 42. Please include the error and the code in the question.463035818_is_not_a_number
Have you tried making test() in the base class virtual?George
sorry i forgot to add the protected in derived class access specifierSelva Bharathi
thats how protected inheritance works, why did you choose to use protected inheritance?463035818_is_not_a_number

2 Answers

0
votes

Edit The code in the question changed so I change the whole answer:

both Private and protected inheritance allow overriding virtual functions in the private/protected base class, neither claims the derived is a kind-of its base. So ptr=&obj; doesn't work because they are not the same type.

protected inheritance allows derived classes of derived classes to know about the inheritance relationship. Thus your grand kids are effectively exposed to your implementation details. This has both benefits (it allows derived classes of the protected derived class to exploit the relationship to the protected base class) and costs (the protected derived class can’t change the relationship without potentially breaking further derived classes).

0
votes

As you are using protected inheritance to the outside world derived is not derived from base, only derived and its subclasses know that it is derived from base.

Therefore:

base *ptr;
derived obj;
ptr=&obj;

Is assigning derived* to the completely unrelated type base*. If you want derived to be convertible to base you need to use public inheritance, protected inheritance deliberately hides your base class from the outside world.