|
Objects in C++
CptS 355 - Programming Language Design Washington State University |
|
C++C++ GoalsC++ Problem AreasGoal here is not to pick on C++ but to point out areas that may be especially problematic.
C++ Constructors
Note: constructors in C++ are class methods ~ they are called without naming any particular instance. C++ classes, unlike python classes, are not themselves objects. DestructorsEvery object has a destructor, either default or programmer-provided. The default destructor for an object calls the destructor of each data member. Destructors are instance methods: if a class is used as a base class its destructors should be made virtual ~ so that dynamic dispatch chooses the right one in all cases.Visibility attributes of methods and data
Virtual vs. non-virtual member functionsDynamic dispatch (see last time) is only used for virtual member functions. For non-virtual member functions the code corresponding to a name is chosen based on the static type of the variable used in making the call. This may not be the right code!Only virtual methods can be overridden in derived classes. But (and this is confusing) non-virtual methods can be overloaded. The behaviors of the two are quite different. By default member functions are non-virtual. The overload/override problem in a nutshell:
Object implementation - single inheritance case
You can’t create an instance of an abstract class: it must be sub-classed and the missing member functions supplied in order to create instances. However you can declare pointers and references having as type an abstract class. Knowing the abstract class is sufficient for the compiler to determine the layout of the vtable which is what it needs in order to compile code using a pointer or reference. |
|