简体   繁体   中英

C++ Expand class Base with class Derived that contains a function returning a * b from base class

class Base {
public :
Base ( int a , int b ) : a ( a ) , b ( b ) { }
protected :
int a , b ;
} ;

I have this class called Base, how do I create an inherited class Derived with a function that will multiply protected members a and b?

class Derived : public Base {
public:
    void print() {
        cout << a * b;
    }
};

int main() {
    Base b(2, 3);
    Derived d;
    d.print();
}

This is what I attempted but I get error message ' the default constructor of "Derived" cannot be referenced -- it is a deleted function

The error is because there's no valid Derived constructor.

Do something like this:

class Derived : public Base {
public:
    using Base::Base;  // Use the Base class constructor as our own

    // Rest of Derived class...
};

Then define a single variable of the Derived class:

Derived d(2, 3);
d.print();

Node that with your current code, you attempt to define two different and unrelated variables b and d .

Derived doesn't have a default constructor so you can't do

Derived d;

You could add one though - and bring in the Base constructors while you're at it:

class Base {
public:
    Base() : Base(0, 0) {}  // now Base has a default ctor
    Base(int a, int b) : a(a), b(b) {}

protected:
    int a, b;
};

class Derived : public Base {
public:
    using Base::Base;      // and now Derived can also use it
    void print() { std::cout << a * b; }
};

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