Technical questions

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

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值