constructor syntax

Started by
5 comments, last by SiCrane 19 years, 5 months ago
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
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.
I'm not refering to syntax error, but more to is there an advantage one over the other?
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;};
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.
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.
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.

This topic is closed to new replies.

Advertisement