Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override member field in derived classes

Tags:

c++

c++11

I have a code snippet below:

#include <iostream>

using namespace std;

class Base {
public:
    Base() : b(0) {}
    int get();
    virtual void sayhello() { cout << "Hello from Base with b: " << b << endl; }
private:
    int b;
};

int Base::get() {sayhello(); return b;} 

class Derived : public Base {
public:
    Derived(double b_):b(b_){}
    void sayhello() { cout << "Hello from Derived with b: " << b << endl; }
private:
    double b;
};

int main() {
    Derived d(10.0);
    Base b = d;

    cout << "Derived b: " << d.get() << endl;
    cout << "Base b: " << b.get() << endl;
}

Run the compiled executable and I find the result is out of my expectation on my llvm-g++ 4.2 machine. The output on my box is as

Hello from Derived with b: 10
Derived b: 0
Hello from Base with b: 0
Base b: 0

What I want to do in the code is to override a member field (b) in Derived class. Since I think both Base and Derived need to access this field, I define a get member function in Base, thus Derived can inherit it. Then I try to get the member field from different objects.

The result shows that I still get original b in Base by d.get() instead of that in Derived, which is what I expected the code to do. Anything wrong with the code (or my understanding)? Is this behavior specified in the specification? What is the right way to override a member field and properly define its getter and setter?

like image 666
Summer_More_More_Tea Avatar asked Oct 10 '13 08:10

Summer_More_More_Tea


People also ask

What is overriding member function in C++?

Function overriding in C++ is a feature that allows us to use a function in the child class that is already present in its parent class. The child class inherits all the data members, and the member functions present in the parent class.

How do you override a field in C#?

Overriding Properties in C# Like methods, we need to use virtual keyword with the property in the parent class and override keyword with the porperty in the child class.

Can derived class use private members?

Private members of the base class cannot be used by the derived class unless friend declarations within the base class explicitly grant access to them.

Can I override a non-virtual function?

You cannot override a non-virtual or static method. The overridden base method must be virtual , abstract , or override . An override declaration cannot change the accessibility of the virtual method. Both the override method and the virtual method must have the same access level modifier.


1 Answers

The new b added in the derived class doesn't override base's b. It just hides it.

So, in the derived class you have two b and the virtual method prints corresponding b.

like image 101
masoud Avatar answered Sep 18 '22 21:09

masoud