Reputation: 13
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;
}
Upvotes: 1
Views: 55
Reputation: 11807
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
{
//...
}
Upvotes: 2