C++ Tips |
| Copyright © 2009 by Zack Smith. All rights reserved. IntroductionThis is just a page where I'm putting some minor details about C++.The ListWhat are the expressions after a method declaration beginning with a colon for?
Foo () : a(5), b("foo")
{
int a;
std::str b;
}
They are the base initialization list.
They can only be used with constructors.
They are a convenient way to initialize variables before the code of the
constructor is run.
For instance, if you have a const value you can set it
once and for all in the initialization list.
It could be argued that initialization lists make C++ code more readable.
How does const work?Theconst keyword is a source of much confusion for programmers.
There are three basic things to remember:
What is the commonly used "= 0" after a virtual function declaration?This indicates that the class will not define the method function since it is a "pure virtual" method. Use it if you are creating an interface class i.e. one that defines an interface without providing any concrete code.Do subclass destructors replace parent class destructors?No. The subclass destructor is called, then the parent, then its parent if any. If a subclass pointer is changed to a parent class pointer however, only the parent class destructor will be called.What is a virtual destructor for?Imagine that you have for some reason converted the pointer of a derived-class object to a pointer of its parent class. Then you delete that object using that parent-class pointer. Normally only the parent-class destructor would be called; that's just how C++ works.By making a parent class's destructor virtual, C++ is forced to call the proper derived-class destructors first.
class X {
public:
X () { puts ("X constructor"); }
virtual ~X () { puts ("X destructor"); }
};
class Y: X {
public:
Y () { puts ("Y constructor"); }
~Y () { puts ("Y destructor"); }
};
main()
{
Y *b = new Y();
X *a = (X*) b;
delete a;
}
This will print:
X constructor Y constructor Y destructor X destructor Links
|
|