简体   繁体   中英

How to access derived data from base class C++

class B :I'm in this type of scenario in my project, where I'm in x() function of base class A and need to access the data y from derived class C . I have declared the object of derived class C and using obj_c i got to the x() function

class A
{
private :
    public :
    //.....
    void x()
    {
        cout << y ;
    }
    //.....
};

class B : public A
{
public :
    //.....
protected :
    //.....
private :
    //.....

};
class C : public B
{
public :
    //.....
protected :
    int y = 10 ;
private :

    //.....

};
int main()
{
    C obj_c ;
    obj_c.x();
}


Place the declaration of y inside the base class. After all, the way you've written your code, A needs to contain ay in order to function.

The derived class can then assign the value by passing it up to A at construction.

class A {
public:
   void x() { cout << y; };

protected:
   A(int value) : y(value) {} 
   int y;
}

class B : public A
{
protected:
    B(int value) : A(value) {}
}

class C : public B
{
public:
    C() : B(10) {}
}

As C inherits from B and B inherits from A, then make function virtual in class. implement it in C and call it directly.

The idea of a base class is that A might be used even if C didn't exist. So where is A going to get y ?

What you do in those cases is the Template Method design pattern:

A assumes that inheriting classes will provide a y by requiring that they implement a get_y() method:

#include <iostream>

class A
{
    private :
    protected:
        virtual int get_y() = 0;
    public :
        //.....
        void x()
        {
            std::cout << get_y() << std::endl;
        }
        //.....
};

class B : public A
{
    public :
        //.....
    protected :
        //.....
    private :
        //.....

};
class C : public B
{
    public :
        //.....
    protected :
        int get_y()
        {
            return 10;
        }
    private :

        //.....

};
int main()
{
    C obj_c ;
    obj_c.x();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM