Q: What is the Object Slicing?
derived class object can be assigned to a base class object, but the other way is not possible.
class Base { int x, y; }; class Derived : public Base { int z, w; }; int main() { Derived d; Base b = d; // Object Slicing, z and w of d are sliced off } |
We can avoid above unexpected behavior with the use of pointers or references. Object slicing doesn’t occur when pointers or references to objects are passed as function arguments since a pointer or reference of any type takes same amount of memory.
Base & b = d
Q: What is the difference between a "assignment operator" and a "copy constructor"?
In assignment operator, you are assigning a value to an existing object.
But in copy constructor, you are creating a new object and then assigning a value to that object.
For example:
complex c1,c2;
c1=c2; //this is assignment
complex c3=c2; //copy constructor
In assignment operator, you are assigning a value to an existing object.
But in copy constructor, you are creating a new object and then assigning a value to that object.
For example:
complex c1,c2;
c1=c2; //this is assignment
complex c3=c2; //copy constructor
Q: How can I handle a constructor that fails?
A: throw an exception.
Q: How can I handle a destructor that fails?
A: Write a message to a log-_le. But do not throw an exception. The C++ rule is that you must
never throw an exception from a destructor that is being called during the "stack unwinding"
process of another exception.
Q: Should my constructors use "initialization lists" or "assignment"?
A: Initialization lists. In fact, constructors should initialize as a rule all member objects in the
initialization list. One exception is discussed further down.
Consider the following constructor that initializes member object x_ using an initialization list:
Fred::Fred() : x_(whatever) { }. The most common benefit of doing this is improved
performance.
Q: How virtual functions are implemented C++?
A: Virtual functions are implemented using a table of function pointers, called the vtable. This table is created by the constructor of the class.
If the derived class overrides any of the base classes virtual functions, those entries in
the vtable are overwritten by the derived class constructor. This is why you should never call
virtual functions from a constructor:
Operators overloading
Following is the list of operators, which can not be overloaded:
::
|
.*
|
.
|
?:
|
No comments:
Post a Comment