a short question:
If I have a class with a pointer as a member and I call the standard constructor: Will the pointer be initialized to the nullpointer?
What if the pointer points to another class?
1 2 3 4 5 6 7 8 9 10 11
class event{
public:
segment* seg;
event();
}
int main(){
...
event nextevent;
...
}
First off defining "seg" in the public section of the class tends to defeat the purpose of the class. You might as well use a "struct".
Generally when an object of the class is created variables are not given any initial value. This is the job of the default or overloaded ctor (constructor). Since thee ctor and dtor are member functions of the class they have access to the "private" variables. Therefor the default or overloaded ctor should initialize the variables.
Something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
class Event
{
public:
Event();
~Event();
private:
segment* seg;
};
Event::Event()
{
seg = nullptr;
}
Event::~Event()
{
}
As of C++ 11 one can initialise member variables in the declaration, it's the same as if it were done via a member initialisation list, in the default ctor, it saves some typing:
1 2
private:
segment* seg = nullptr;
This is better than initialising in the ctor body, it avoids a default init, followed by the one in the ctor.
Then have another ctor with a member initialisation list, that initialises all the member variables with objects. Or have a member function that sets it's value later - if you need to change it at run time.
Also, if you're using a pointer, you should ask yourself "who owns the pointer?" In other words, who, if anyone, is responsible for deleting what it points to? For memory management, it's important to be crystal clear on this and then be sure that your code follows the policy you define. Be sure to document in your class who owns the pointer.