Home > Blockchain >  C Expand class Base with class Derived that contains a function returning a * b from base class
C Expand class Base with class Derived that contains a function returning a * b from base class

Time:09-18

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

CodePudding user response:

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.

CodePudding user response:

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; }
};
  • Related