Peter Stewart
Peter Stewart

Reputation: 3017

How can I use an initialization list to select which constructor to use?

I just asked this question and the good answers mentioned using an initialization list. So I looked it up in many various places. It was often said that one can use an initialization list to select which constructor to use.

class First
   {private: 
         int a, b, c;
  public:
First(int x);
First(int x, int y);
}

First::First(int x, int y, int z = 0)
{ /* this is a constructor that will take two or three int arguements. */ }

First::First(int x, int y = 0, int z = 0)
{ /* and this will be called if one arguement is given */ }

I thought all assignments should be avoided, so how would I write the initializer lists for these two constructors?

Upvotes: 0

Views: 1041

Answers (4)

graham.reeds
graham.reeds

Reputation: 16476

I think you mean this:

class First
{
private: 
    int a, b, c;
public:
    First(int x);
    First(int x, int y);
}

class Second
{
private:
Second(int x) : First(x) { }
Second(int x, int y) : First(x, y) { }
}    

Maybe?

Upvotes: 1

GManNickG
GManNickG

Reputation: 503953

I'm not quite sure I follow. As it stands, by providing an argument to x and y (and therefore z), both constructors will be available to call, resulting in ambiguity.

I think what you're looking for is:

class First
{
public:
  First(int x);
  First(int x, int y, int z = 0);
};    

// invoked as First f(1);
First::First(int x) :
a(x), b(0), c(0)
{}

// invoked as First f(1, 2); or First f(1, 2, 3);
First::First(int x, int y, int z) :
a(x), b(y), c(z)
{}

Upvotes: 3

Benoît
Benoît

Reputation: 16994

This is not how things work. If you want to use default arguments, use only one constructof, declare it with default arguments, and define it (without redefining them).

class First
{
  private: 
         int a, b, c;
  public:
First(int x, int y = 0, int z = 0);
};

First::First(int x, int y, int z)
{   /*...*/ }

Considering your question, i am not sure you know what an initialisation list is...

Upvotes: 1

Ctor initialization list isn't for the purpose of choosing which ver of ctor will be chosen.

Upvotes: 1

Related Questions