Sign in to follow this  
devgooru

constructor syntax

Recommended Posts

Is there a difference between these two syntax for constructors?
[source lang="cpp"
//version 1
class Base
{
 public:
  Base(int);
  ~Base();
 private:
  int x;
};

Base::Base(int y)x(y)
{}

//version 2
class Base
{
 public:
  Base(int);
  ~Base();
 private:
  int x;
};

Base::Base(int y)
{
  x = y;
}

I read this from teach yourself c++ in 21 days

Share this post


Link to post
Share on other sites
Syntax errors aside, tbe second form uses a member initialization list. For primitive types, it doesn't really matter if you initialize something with an assignment in the constructor's body or in the initializer list. For more complex types, it's more efficient to use the intializer list.

The difference is that if you initialize something with assignment in the body, you have the cost of constructing the object and then assigning to it. With the initializer you construct it directly.

Share this post


Link to post
Share on other sites
So this would be the same when you are initializing a variable such as:

int x(5);


?

Also, this is a great forum, but is this the right place to post such questions? I read about comp.lang.c++ forum, but have yet to fully understand how to post/reply.

Share this post


Link to post
Share on other sites
Pretty much, but when declaring variables, the two forms
int x(5);
and
int x = 5;

do the same thing. This goes even for more complex types, so

string foo = "Hello";

and
string foo("Hello");
do the same thing too. However, something like
string foo = "Hello";
is different from
string foo;
foo = "Hello";


The first invoke the constructor with "Hello" as an argument, the second default constructs the string and then assigns "Hello" to it.

Oh and there's nothing wrong with posting basic C++ questions here. It's one of the reasons we have a For Beginners forum.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this