I had just a problem with the sample code written in
c++ primer plus 6th edition page574-code 14.15 stcktp1.h
and code 14.16stkoptr1.cpp
The author declared
1 2 3 4
class Stack{
private:
int top;
...
but does not initialize top to 0, which cause my program unable to run on ubuntu
system using -std=c++11
I just found it a good example to prove what the author said:Always give those variable a default value...
Before you get all excited you should check the ctor for the class because that is where variables should be initialized.
As I understand it in a struck you can initialize variables, but in a class it it different because a class does not exist until you construct one as in main like Stack stack;. This invokes the ctor to construct the object and any variables you set in the ctor will give the class variables an initial value.
I could be a bit off here, but the concept has the right idea.
As I understand it in a struck you can initialize variables, but in a class it it different because a class does not exist until you construct one as in main like Stack stack;. This invokes the ctor to construct the object and any variables you set in the ctor will give the class variables an initial value.
In C++ the only difference between a struct and a class is the default access mode. With a stuct the default access mode is public and a class has a default access mode of public. Everything else is the same including that a class and a struct have "default" constructors, destructors, and copy constructors.
Thanks for the input. I see that my understanding of "structs" is a bit off. Then again I mainly use a "struct" to hold multiple variables and do not get into ctors, detors and functions that much.
Initializing variables inside a "struct" seamed to work whereas it did not inside a class unless through the ctor.
I will have to make my point clearer in the future.
Line 6 and line 11 is called a default member initializer. It will be used to initialize the member variable if it's not explicitly initialized by the constructor in the member initializer list. The initialization still happens in the constructor as if the member initializer list was used so don't make the mistake and think they are initialized before the ones that are explicitly listed in the member initializer list.
This feature can be useful when you have multiple constructors and you don't want to repeat the default value.