Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't get composition right

I'm honestly embarassed I have to ask but I'm stuck on that.

#include <iostream>
using namespace std;

class Obj
{
};


class Test
{
private:
  Obj a;

public:
  Test(Obj _a)
    : a(_a) 
  {}
};


int main() {

  Obj ob();
  Test t(ob);

  return 0;

}

I get this error:

t.cpp:24: error: no matching function for call to ‘Test::Test(Obj (&)())’
t.cpp:15: note: candidates are: Test::Test(Obj)
t.cpp:10: note:                 Test::Test(const Test&)

I don't get it. The same snippet works just fine with built in types (integers and stuff).

like image 687
user3609293 Avatar asked Apr 15 '26 14:04

user3609293


2 Answers

Obj ob(); declares a ob to be a function taking no parameters and returning Obj.

If you want to default construct an Obj, use Obj ob; or Obj ob{};.

like image 152
Mankarse Avatar answered Apr 17 '26 06:04

Mankarse


This line

Obj ob();

does not create an object ob. It declares a function that takes nothing as input and returns a Obj.

Change it to:

Obj ob;
like image 35
R Sahu Avatar answered Apr 17 '26 04:04

R Sahu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!