Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiating an object as class member without default constructor

Tags:

c++

I am a newbie to C++. I want to declare an object as a private member of another class. Is the instantiation of this object can be done with out the default constructor? A sample code is listed here:

class Vertex{
  int i;
public: 
  Vertex(int j):i(j){};
  Vertex(const Vertex & v){i=v.i;};
}

class Test{
  Vertex v;
public:
  Test(const Vertex & v1){v(v1);}
}

int main()
{//some code here;
  Vertex v1(int j=1);
  Test(v1); // *error: no matching function for call to 'Vertex::Vertex()'*
  return 0;
}

It appears to me once declared an object as a private class member (e.g. Vertex v), the default constructor is immediately sought after. Anyway to avoid this? Thanks a lot.

like image 636
Void Avatar asked Sep 10 '25 04:09

Void


1 Answers

Vertex v1(int j=1);

This declares a function, v1, which returns a Vertex and takes an int argument. What you want is

Vertex v1(1);

in addition, you need to use initialiser lists as the other answers have shown:

Test(const Vertex & v1) : v(v1) {}
like image 55
Konrad Rudolph Avatar answered Sep 12 '25 18:09

Konrad Rudolph