Using constructor in constructor
Hello. I am trying to use constructor within constructor in the same class. Is that possible. I have tried something and it shows me a error message:
error: type ‘mainClass’ is not a direct base of ‘glavna’
This is the program I tried:
Code:
class mainClass
{
private:
int x,y;
public:
// constructors
mainClass(int a, int b) {x=a; b=y;}
mainClass():glavna(0,0) {}
int getX() {return x;}
int getY() {return y;}
};
Thank you!!!
Re: Using constructor in constructor
Quote:
Originally Posted by
depecheSoul
Hello. I am trying to use constructor within constructor in the same class. Is that possible. I have tried something and it shows me a error message:
What is "glavna"? It is not declared anywhere in that code you posted.
Regards,
Paul McKenzie
Re: Using constructor in constructor
glavna is mainClass i forgot to translate it, when I copy/paste code in the forum Sorry.
Code:
class mainClass
{
private:
int x,y;
public:
mainClass(int a, int b) {x=a; b=y;}
mainClass():mainClass(0,0) {}
int getX() {return x;}
int getY() {return y;}
};
Re: Using constructor in constructor
This specific case can be handled quite simply by providing default values for the two constructor parameters:
Code:
class mainClass
{
private:
int x,y;
public:
mainClass(int a = 0, int b = 0) {x=a; b=y;}
int getX() {return x;}
int getY() {return y;}
};
That way you can construct mainClass objects by providing either two or no arguments. You can even pass only one, which then will correspond to a, and b gets the default value of 0.
However, there are more complex cases that can't be solved that simply, and it is not possible to define a class' constructor in terms of another constructor of the same class. The common solution to this is to factor out the initialization code common to various constructors into a private initialization member function and then call that from the individual constructors.
Re: Using constructor in constructor
Quote:
Originally Posted by Eri523
However, there are more complex cases that can't be solved that simply, and it is not possible to define a class' constructor in terms of another constructor of the same class.
It is possible, but you need a compiler on the bleeding edge (e.g., g++ 4.7 supports delegating constructors, but it is not a stable release yet).
Re: Using constructor in constructor
Quote:
Originally Posted by
laserlight
It is possible, but you need a compiler on the bleeding edge (e.g., g++ 4.7 supports delegating constructors, but it is not a stable release yet).
Fascinating! :) Didn't know that. Am I right to assume this is a C++11 feature?
At any rate, thanks for pointing that out.
Re: Using constructor in constructor