简体   繁体   中英

Overriding Private Members of Parent Class

Given the following classes:

class foo
{
private:
    int c;

public:
    foo( int a = 42 ) { c = a; }
    ~foo();
};

class bar: public foo
{
public:
    bar();
    ~bar();
};

How can I make bar override c with a different number? Can I do something like this?

bar::bar() 
{
    c = 12;
}

I get this error when trying to compile:

test.cpp: In constructor 'bar::bar()' :
test.cpp:8:7: error: 'int foo::c' is private

Call your base class' constructor in the constructor initialization list:

bar::bar()
  : foo(12)
{ }

Incidentally, you should always prefer using a constructor initialization list over assignment inside the constructor body, so your foo constructor would be better written as:

foo( int a = 42 ) : c(a) { }

Call the base class constructor:

bar::bar() : foo(12) { }

Edit: whoops

You should use getter and setter methods for your private variables.

So your calls foo should look like this:

class foo
{
private:
    int c;

public:
    foo( int a = 42 ) { c = a; }
    virtual ~foo();
    void setC (int tempC){
         c=tempC;
    }
    int getC() const{
        return c;
    }
};

In the constructor of B you can call them the setter method:

bar::bar() 
{
    setC(12);
}

You should then always use your setter and getter methods to access your variable, instead of accessing it direct.

You should also declare your destructor of your base class virtual.

关于什么

bar::bar() : foo(12) {}

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