Building constructors with shared functionality

A

Aguilar, James

I want to call a constructor from another constructor without constructing
an object. In other words, I want to partially initialize the object I'm
working with with one constructor, and finish the job with another.

class Foo
{
public:
Foo();
Foo(int i);
private:
int a, b;
};

Foo::Foo()
{
a = b = 0;
}

Foo::Foo(int i)
{
Foo(); //or should it be Foo::Foo()?
a = i;
}

Is there any way to do this in C++ that does not involve private helper
methods?
 
J

John Harrison

I want to call a constructor from another constructor without
constructing
an object. In other words, I want to partially initialize the object I'm
working with with one constructor, and finish the job with another.

class Foo
{
public:
Foo();
Foo(int i);
private:
int a, b;
};

Foo::Foo()
{
a = b = 0;
}

Foo::Foo(int i)
{
Foo(); //or should it be Foo::Foo()?
a = i;
}

Is there any way to do this in C++ that does not involve private helper
methods?

No. But if you really need a partially initialised object that might be a
clue that what you really need is to split your object into a base class
and a derived class. While the derived class is being created the base
class will be created first and that is your 'partially initialised
object'.

john
 
S

Sharad Kala

Aguilar said:
I want to call a constructor from another constructor without constructing
an object. In other words, I want to partially initialize the object I'm
working with with one constructor, and finish the job with another.

class Foo
{
public:
Foo();
Foo(int i);
private:
int a, b;
};

Foo::Foo()
{
a = b = 0;
}

Foo::Foo(int i)
{
Foo(); //or should it be Foo::Foo()?
a = i;
}

http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.3
You can't call a constructor. Foo() in your above definition of Foo(int i)
is a temporary object, it doesn't call the constructor. Instead write some
private member function init and call it.
-Sharad
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top