-3

i need to get clear about, the best way to call the super class constructor/method explicitly.

I tried with the following both way to call superclass constructor:

Myclass::Myclass(int a, int b):X(a),Y(b)
{
    // do something
}

and

Myclass::Myclass(int a, int b)
{
X = a;
Y = b;
}

So my question over here is:

  1. Which is the best way to call super class constructor/method explicitly?
  2. And what are the benefits will get in both way?
  3. what is the best practice and why?
  4. There is any performance issue lies with both way?

Regarding my question i found this link: What are the rules for calling the superclass constructor? but still i have little more doubt what i asked above.

if there is any online tutorial, blog or video also u can mention over here, it will great help full for me. Thank in advance.....

Community
  • 1
  • 1
nagarajan
  • 474
  • 3
  • 21
  • 3
    The second one doesn't do what you think it does. (and if `X` and `Y` don't both have default constructors, it shouldn't even *compile*). Edit: now it will only compile if X and Y are member variables. – WhozCraig Feb 12 '15 at 08:57
  • 2
    In what way is the question you linked unclear? – Rerito Feb 12 '15 at 08:57
  • @WhozCraig Or having a non-explicit constructor taking an int – Rerito Feb 12 '15 at 09:01
  • are `X` and `Y` supposed to be both direct base classes of `Myclass` ? – M.M Feb 12 '15 at 09:04
  • @WhozCraig if `X` is the name of a type then `X = a;` shouldn't compile regardless of presence of a default constructor – M.M Feb 12 '15 at 09:04
  • yes 'X' and 'Y' are the direct base class of 'MyClass` – nagarajan Feb 12 '15 at 09:05
  • 1
    @MattMcNabb if they were the names of instance vars it will compile in *both* examples. But we just found out they're both types, so the second is still junk. Wouldn't a **real** code example have been handy? You may have arrived late. The original post of the second constructor looked as it does in stensoft's answer. It has since changed. – WhozCraig Feb 12 '15 at 09:07

1 Answers1

4

The only correct way to call superclass's constructor is from the initialization list:

Myclass::Myclass(int a, int b)
    :X(a),Y(b)
{}

The other way in fact calls different constructors:

Myclass::Myclass(int a, int b)
    // implicit :X(),Y()
{
    // These two don't call constructors but actually declare variables
    X(a);
    Y(b);
}
StenSoft
  • 9,369
  • 25
  • 30