Base-derived class init sequence (member variable and constructor body)
class MemA { public: MemA(){ cout << "MemA" << endl; } };
class MemB { public: MemB() { cout << "MemB" << endl; } };
class A
{
public:
A() { cout << "class A" << endl; }
MemA val_a;
};
class B: public A
{
public:
B() { cout << "class B" << endl; }
MemB val_b;
};
output:
MemA
class A
MemB
class B
Can default contructor contain parameters?
Yes
A default contructor can contain default parameters
Can I create object array of the class without default constructor?
No
class X
{
public: X(int i) {}
};
...
X obj[10]; //fail to compile!!
Can constructor be virtual?
No
a) No need to override
b) No vtable available when calling constructor
how to handle error in constructor?
1)because constructor has no return value, throw exception and set the internal status to "Zombie"
2)No initialization in constructor, provide a explicit Init() function for users
3)make constructor private/protected, provide a CreateObject() function and do the check there.
What is “delete this”?
1)restrict to creating stack object
2)using in ref count technique
class DeleteThis
{
private:
~DeleteThis() {}; // can't create stack object
public:
int data;
void Release() { delete this;}
};
DeleteThis *p = new DeleteThis;
p->data = 10;
p->Release();
//cout << p->data << endl; //error refer to p
pass value to copy constructor is invalid
pass value to operator = is good
---------------------------------------------------------------------------------
Because if it's not by reference, it's by value. To do that you make a copy, and to do that you call the copy constructor. But to do that, we need to need to make a new value, so we call the copy constructor, and so on...
(You would have infinite recursion because "to make a copy, you need to make a copy".)
class BadCtor {
public:
BadCtor(const BadCtor /*&*/ o) {} // fail to compile!!
};
class GoodCtor {
public:
GoodCtor(const GoodCtor &o) {}
GoodCtor &operator=(const GoodCtor /*&*/ o){} // this one is OK as well
};
Write some code could be compiled in C but not in C++
int class = 0