user1840302
user1840302

Reputation: 195

C++ delegating constructors

Hello i am more familiar with Java than C++

test.h:

class Test
{
private:
int a,b,c;
public Test(int a, int b, int c);
}

test.c

Test::Test(int a, int b, int c)
{
this->a = a;
this->b = b;
this->c = c;
}
Test::Test(int a, int b)
{
this(a, b, 0);
}
Test::Test(int a)
{
this(a, 1)
}
Test::Test()
{
this(2)
}

1 - Do i have to type each constructor signature in test.h ?

2 - How can i write multiple definitions of constructors ?

3 - I read you can combine multiple constructors in 1 definition using default values. How is that done

Thank you

Upvotes: 2

Views: 1033

Answers (4)

Richard Hodges
Richard Hodges

Reputation: 69892

as of c++11 one constructor may defer to another. So if you want to avoid publishing the default values in the interface you can do it this way:

// declaration
struct X
{
    X(int a, int b, int c);
    X(int a, int b);
    X(int a);
    X();

private:
    int a,b,c;
};

// definition    
X::X(int a, int b, int c)
: a(a), b(b), c(c)
{}


X::X(int a, int b)
: X(a, b, 2)
{
}


X::X(int a)
: X(a, 1, 2)
{
}

X::X()
: X(0,1,2)
{
}

Upvotes: 2

cdonat
cdonat

Reputation: 2822

delegating constructors is only available in C++11. The syntax looks like this:

Test::Test(int a1, int b1, int c1) :
    a{a1}, b{b1}, c{c1}
{}

Test::Test(int a, int b) :
    Test(a, b, 0)
{}

Test::Test(int a) :
    Test(a, 1)
{}

Test::Test() :
    Test(2)
{}

I have also used the initialization syntax in the first constructor. It is preferable to do so, because otherwise the member object will be initialized with the default constructor and then assigned a new value.

Upvotes: 0

Simple
Simple

Reputation: 14390

Your constructor delegation syntax is wrong. You need to use the member initialiser list to delegate to a different constructor:

Test::Test(int a, int b)
    : Test(a, b, 0)
{
}
Test::Test(int a)
    : Test(a, 1)
{
}
Test::Test()
    : Test(2)
{
}

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234715

  1. Yes

  2. Type them out

  3. Why not use Test(int _a, int _b = 1, int _c = 0);

and define with

Test::Test(int _a, int _b, int _c) : a(_a), b(_b), c(_c)
{
}

i.e. supply default values and use base member initialisation?

This is also available pre C++11

Upvotes: 0

Related Questions