Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a base class member in derived class

I have a simple class as below

class A {
protected:
    int x;
};
        
class B : public A {
public:
    int y;

    void sety(int d) {
        y = d;
    }

    int gety() {
        return y;
    }
};
    
int main() {
    B obj;
    obj.sety(10);
    cout << obj.gety();
    getch();
}

How can I set the value of the protected instance variable A::x from an instance of the derived class B without creating an instance of class A.

EDIT: Can we access the value of A::x using the object of B? Like obj.x?

like image 432
Vijay Avatar asked Mar 01 '11 11:03

Vijay


People also ask

Can base class access derived class members in Java?

// As base-class pointer cannot access the derived class variable.

How do I access base class members?

The base class members can be accessed by its sub-classes through access specifiers. There are three types of access specifies. They are public, private and protected. When the base class is publicly inherited, the public members of the base class become the derived class public members.

How do you access the members of base class in a derived class in Python?

This is really simple, you just have to call the constructor of parent class inside the constructor of child class and then the object of a child class can access the methods and attributes of the parent class.

Can you access the derived classes default members in base class?

Private members can only be accessed by member functions of the same class or friends. This means derived classes can not access private members of the base class directly!


1 Answers

B is an A, so creating an instance of B is creating an instance of A. That being said, I'm not sure what your actual question is, so here's some code that will hopefully clarify things:

class A
{
protected:
    int x;
};

class B : public A
{
public:
    int y;

    int gety() const { return y; }
    void sety(int d) { y = d; }

    int getx() const { return x; }
    void setx(int d) { x = d; }
};

int main()
{
    B obj;

    // compiles cleanly because B::sety/gety are public
    obj.sety(10);
    std::cout << obj.gety() << '\n';

    // compiles cleanly because B::setx/getx are public, even though
    // they touch A::x which is protected
    obj.setx(42);
    std::cout << obj.getx() << '\n';

    // compiles cleanly because B::y is public
    obj.y = 20;
    std::cout << obj.y << '\n';

    // compilation errors because A::x is protected
    obj.x = 84;
    std::cout << obj.x << '\n';
}

obj can access A::x just as an instance of A could, because obj is implicitly an instance of A.

like image 152
ildjarn Avatar answered Oct 20 '22 22:10

ildjarn