1

I am learning C++ and came across this code where the constructor is initialised without declaring member variables. Also, the object is created without any parameters. Wouldn't a default constructor be called instead?

Also, if this class is inherited, will the derived class have access to x and y?

// Example program

#include <iostream>
#include <string>

class game
{
public:
    game(int x = 0, int y = 100); // Do they get defined as members?
    int z; 
};

game::game(int x, int y) : z(x)
{
    std::cout << x;   
}

int main()
{
    game g; // passed w/o parameters.
    return 0; 
}
TriskalJM
  • 2,393
  • 1
  • 19
  • 20
Cleverboy
  • 13
  • 2
  • They could have access to x and y through a base class constructor called from the derived class. – Arnav Borborah Jun 08 '17 at 13:14
  • 1
    Since you give default arguments to all of the arguments of the constructor, it becomes the default constructor since it can be called without specifying any arguments. – Some programmer dude Jun 08 '17 at 13:14
  • 1
    And as with any function, arguments behaves as local variables, and go out of scope once the function returns. That happens for constructors as well. Neither constructor arguments nor constructor local variables becomes member variables of the class. – Some programmer dude Jun 08 '17 at 13:15
  • 2
    `x` and `y` are parameters of the constructor only, they are not members of the object. You might want to solidify your understanding using a [good C++ book](https://stackoverflow.com/q/388242/1782465). – Angew is no longer proud of SO Jun 08 '17 at 13:19
  • Oh Ok. Interesting. Thank you so much. I tried to display the value of x by using a display function. It says x was not declared in scope. class game { public: game(int x = 0, int y = 100); int z; void display(); };int main() { game g; g.display(); return 0; } – Cleverboy Jun 08 '17 at 13:22

1 Answers1

2

Also the object is created without any parameters. Wouldn't a default constructor be called instead?

You declare your constructor as follows:

game(int x = 0, int y = 100);

And the implementation:

game::game(int x, int y) : z(x)
{
    std::cout << x;   
}

Since you have specified default arguments for the constructor, when you call:

game g;

It is the same as calling:

game g {0, 100};

Since the default arguments are provided for the constructor.

game(int x = 0, int y = 100); // Do they get defined as members.

They don't get defined as members, unless you set their values to members in the class. x and y both go out of scope at the end of the constructor.

Also, if this class is inherited will the derived class have access to x and y?

Not directly, which you can see as follows:

class Derived : public game
{
public:
    Derived();
};

Derived::Derived() : game(100, 100) //Or whatever arguments
{
    //...
}
Arnav Borborah
  • 11,357
  • 8
  • 43
  • 88