-3
class c1{
public:
    c1(int AO, int AE){
        x=AO;
        y=AE;
    }

private:
    int x,y;
};


class c2{
public:


//c2(int x, int y, bool target): obj1(x, y), flag(target){}


c2(int x, int y, bool target){
  obj1=c1(x,y)
  flag=target;
}

private:
    c1 obj1;
    bool flag;
};

If i write the line with the constructor in the comments, it runs. How can i write c2(int x, int y, bool target) in order to compile? (the error message is not matching function for call to 'c1:c1()')

  • 2
    Use the member initializer list in the `c2` constructor to initialize `obj1`. See [here](https://stackoverflow.com/questions/1711990/what-is-this-weird-colon-member-syntax-in-the-constructor.) – user0042 Dec 12 '17 at 18:38
  • You missed a `;` at the end of `obj1=c1(x,y)`. – Eljay Dec 12 '17 at 18:40
  • There is probably nothing in C++ that has a higher ratio of usefulness to time spent teaching it than the Member Initializer List. – user4581301 Dec 12 '17 at 18:53

1 Answers1

1
c2(int x, int y, bool target): obj1(x, y), flag(target){}

When this starts executing, uses the : calls to determine how to construct each member. This uses the object1(x,y) constructor, then the flag(target) constructor, then calls the body, which is empty. This makes sense.

c2(int x, int y, bool target){
  obj1=c1(x,y)
  flag=target;
}

When this starts executing, it uses the : calls to determine how to construct each member. Since this is empty, it uses the default constructor for obj1 and flag, and then wants to calls the body. But the initial constructor obviously can't compile, because obj1 has no default constructor! no matching function for call to 'c1:c1()'

Mooing Duck
  • 64,318
  • 19
  • 100
  • 158