kingcobra1986
kingcobra1986

Reputation: 971

How do I use the constructor in inherited classes when the parent class doesn't have a default constructor in C++?

I have a programming assignment in one of my college classes. The professor gave us specific code to work off of and told us not to alter his code. I am supposed to make a class called GameMgr that inherits from a class called Mgr. Here is a simplified version of what he gave us for Mgr.h:

class Engine;

class Mgr 
{
public:
    Engine *engine;

    Mgr(Engine *eng);
    virtual ~Mgr();
};

I am attempting to make a class called GameMgr:

class GameMgr: public Mgr
{
public:
    GameMgr(Engine* eng);
    void Run();
};

I get an error when trying to compile the code:

error: no matching function for call to ‘Mgr::Mgr()’
 GameMgr::GameMgr(Engine* eng)
                             ^

I have made a pad on CodePad with an example (The example in the pad is meant just for this question and isn't my actual code but displays the minimum code needed for this question).

I have tried adding a default constructor to my GameMgr class but I still get errors. I'm assuming that it can be done, being that it is code from my professor, but the only way that I know to solve it is by changing the Mgr class to have Mgr().

How do I use the constructor in inherited classes when the parent class doesn't have a default constructor in C++?

I tried the solution for this question: How do I call the base class constructor? in my CodePen example and it still isn't working. Therefore, I do not believe that is a solution to my question.

Upvotes: 0

Views: 77

Answers (1)

Rishi
Rishi

Reputation: 1395

You can try this example. I have used an int for simplification.

#include <iostream>
using namespace std;
class Mgr 
{
public:
    int a;
    Mgr(int _a):a(_a){}
    virtual ~Mgr(){}
};

class GameMgr: public Mgr
{
public:
    GameMgr(int _b):Mgr(_b) {}
    ~GameMgr(){}
    void Run();
};

int main() {
    GameMgr game_mgr(9);
    return 0;
}

Sample-code

Upvotes: 2

Related Questions