fibo11235
fibo11235

Reputation: 163

Do constructors have to initialize member variables in C++?

I have learned that constructors are used to initialize the member variables of a class in C++. In all the examples I have seen the constructors initialize all the member variables of the class when called.

What happens if I write a constructor that only initializes some or none of the member variables?

Upvotes: 2

Views: 2699

Answers (4)

Rakete1111
Rakete1111

Reputation: 48938

It really depends on what member variables you have. If you provide a constructor and don't explicitly initialize a variable in the member initialization list, then it will be default initialized. And this is for every variable.

Now, default initialization does something else depending on what variable you have. If you have a builtin type, like int or bool, then it will not be initialized to 0 or any other value, just like if you had:

int value; // it has an indeterminate value

This also applies to arrays. If it is another class, then the default constructor of that class will be called, just like if you had:

struct Foo { /*something*/ };
Foo value; // calls default constructor, i.e. initializes object

Upvotes: 5

glennmark
glennmark

Reputation: 543

it's fine.. you can also initialize your member variables in your member functions, then, just call the function in the constructor.. the important thing is to don't forget to initialize variables before using them..

in short.. it's fine to not initialize your member variables in the constructor as long as you initialize them somewhere in the class before using them..

Upvotes: 2

Andam
Andam

Reputation: 2167

Depends on the class and your program. Does your class and program needs all of those variables in all of the cases. if your class does require them then no errors or exception will occur otherwise your program might crash or something.

Upvotes: 1

adamfowlerphoto
adamfowlerphoto

Reputation: 2751

You are allowed to do that. It isn't great practise though as you'll have a series of uninitialised member variables that could produce unexpected results

Upvotes: 1

Related Questions