EverSpring working shop

To pursue creative ideas based on nature.

统计

留言簿(1)

他山之石

阅读排行榜

评论排行榜

Constructor usgae in the base type and the derived type

  • When the constructor of the derived class is defined, we should consider and ensure how the base type is initialized:
    • If the base type has default constructor, the constructor in the derived class may ignore the initialization for the memebers in base type.
    • If the base type have no default constructor, the constructor in the derived class should explict initialize the base type in the initialization list via the user defined base type constructor.

 

// testing.cpp : Defines the entry point for the console application.
//

#include 
"stdafx.h"
#include 
"stdio.h"
#include 
<iostream>

using namespace std;

class BASE
{
public:
    BASE(
int x):i(x){};
    BASE()
{};
private:
    
int i;
}
;

class derived: public BASE
{
public:
    derived(
int x):BASE(x)
    
{
        j 
= x;
        
//this->BASE::BASE(x);
    }
;
private:
    
int j;
}
;

class grandson: public derived
{
public:
    grandson(
int x, int y):derived(y),j(x){}//use the defined constructor for derived because no defual contructor defined
private:
    
int j;
}
;

int _tmain(int argc, _TCHAR* argv[])
{
    
int a = 0;
    cout 
<<"debugging";

    BASE base_obj(
5);
    BASE base_obj_2(
7);

    BASE 
*ptr = &base_obj;
    BASE 
*ptr_b = ptr;

    
int sizeofobj = (int)sizeof(base_obj);

    ptr 
= (BASE*)((char*)ptr + sizeofobj);

    derived der_obj(
6);
    derived der_obj_2(
9);

    
//der_obj_2 = base_obj; //there is no acceptable conversion from BASE -> Derived

    base_obj_2 
= der_obj;

    
return 0;
}

posted on 2007-10-21 23:29 everspring79 阅读(261) 评论(0)  编辑 收藏 引用 所属分类: Notes


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理