Search code examples
c++visual-c++constructordefault-constructor

How to use default constructor while using composition? in visual studio


i keep getting when i declare Game object in the main : // C2512: no appropriate default constructor available , I am using visual studio , on other compilers that error doesn't always appear .

I tried to change the way to define and initialize but It keep giving me the same error, something like this was in a question in an exam is to have default parameterized constructor and one of the parameters was another class object in composition, but i do this in the code it gives me the error above

so how to use default constructor while using composition ???

#include <iostream>
#include <string>
//#include "Game.h"
//#include "Screen.h"
using namespace std;


class Screen
{
private:
    int resolution;
    int brightness;
    string color;
public:
    Screen(int br = 20, int rl = 10, string colr = "green");
};

Screen::Screen(int br, int rl, string colr) :resolution(rl), brightness(br), color(colr)  {}



class Game {
protected:
    string name;
    Screen screen1;
public:
    Game(Screen& ok, string nam = "minecraft");
};


Game::Game(Screen& ok, string nam) : screen1(ok), name(nam)
{ }



int main()
{
    //Screen screen1;
    Game gg;




    return 0;
}

//screen1 = ok;



Solution

  • The constractur Game(Screen& ok, string nam = "minecraft"); needs to get a reference to Screen object.

    And when you create Game object like this: Game gg;

    there's no reference to Screen object.

    A good example of a constactur call would be:

    Screen s;
    Game gg(s);
    

    Other tip is the to put the implementation on other file or where you declare it. so

    Screen::Screen(int br, int rl, string colr) :resolution(rl), brightness(br), color(colr) {}

    and Screen(int br = 20, int rl = 10, string colr = "green"); would be:

    Screen(int br = 20, int rl = 10, string colr = "green") 
        :resolution(rl), brightness(br), color(colr)  {}