-2

I am trying to make a constructor for a derived class. Doing it this way doesn't seem to work:

#include <iostream>

class FirstClass
{
public:
    int X;
    FirstClass(int x)
    {
        this->X = x;
    }
    int getXpow() { return pow(X, 2); }

};

class SecondClass : FirstClass
{
public:
    SecondClass(int x)
    {
        FirstClass::FirstClass(X);
    }

    int getXpow() { return pow(X, 3); }
};

int main()
{
    using namespace std;
    FirstClass FCobj(3);
    cout << FCobj.getXpow() << endl;
    SecondClass SCobj(3);
    cout << SCobj.getXpow() << endl;

    system("pause");
    return 0;
}

because it says at the first { bracket of SecondClass(int x) the following thing Error: no default constructor exists for class "FirstClass". And how does constructor inheritance even work?

Alex Azazel
  • 332
  • 5
  • 18

1 Answers1

1

Just use the member initializer list:

SecondClass(int x) : FirstClass(x) {
}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190