• Advertisement
Sign in to follow this  

constructor syntax

This topic is 4839 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
Class 2's constructor should be declared as so:

Base(int y);


NOT

Base(int);


With that, I think you'll see the difference.

Share this post


Link to post
Share on other sites
It's not really which is better, it's what your more comfortable coding. I, myself perfer such:


class Base
{
public:
Base(int x) : y(x) {}
~Baes(){}
private:
int y;
};

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
Sign in to follow this  

  • Advertisement