fdwfg wdfwdfv
fdwfg wdfwdfv

Reputation: 239

Trying to make sense with my understanding with Constructors in CPP

Lets discuss on the next code sample:

class A
{
public:
    int a;
};

class B:public A
{
public:

    int a;
};


int main()
{
    B b;
    std::cout << b.a;
    system("pause");
    return(0);
}

Why if I'm writing its like this, So its cant compiles, and giving me error.

But if I add a constructor to B class, like this:

B()
{
// An empty constructor!!!
}

then it prints on the screen a garbage value ('a' variable value.). And why I don't need any constructor if I'm writing the class like this:

 class B:public A
 {
 public:
     int a = 5;  // 5 is just one of many possibilities...
 };

In that case, 5 will be printed on the screen.

Upvotes: 0

Views: 61

Answers (1)

Lorence Hernandez
Lorence Hernandez

Reputation: 1189

Constructors can be used to assign or initialize values to the data members by doing either one of this:

B()
   :a(5) // intialize a with value 5
{

}

or

B()
{
    a = 5; // assign a with value 5
}

the 2nd one initializes a with garbage value and then assign 5 to it.

data members are initialized before the constructor's body is executed.

And why I dont need any constructor if im writing the class like this:

its not that you dont need constructor, its just that it already has a value.

Upvotes: 2

Related Questions