2

Was asked this question in IBM ISL interview. Can I write a copy constructor for an Abstract base class using pointer instead of reference (&)?

I think it can be used. Any comments/suggestions?

#include <string>

//abstract base class  
class ABC{
    int a;
    int b;
    char *p;
public:
    virtual void f() = 0;
    ABC(){};
    ABC(ABC* abc){
        a = abc->a;
        b = abc->b;
        p = new char[strlen(abc->p)+1];
        p = strcpy(p, abc->p);
    }
};

//derived class  
class ConcreteDerivedClass: private ABC
{
public:
    ConcreteDerivedClass(){}
    void f(){}
    ConcreteDerivedClass(ConcreteDerivedClass& obj):ABC(&obj){}
};
4

3 回答 3

5
ABC(ABC* abc)

This is not copy-constructor.

A copy-constructor must be one of the following forms:

ABC(ABC & abc);
ABC(ABC const & abc);  //most common form
ABC(ABC volatile & abc);
ABC(ABC const volatile & abc);

The second one is most common. So define a copy-constructor of this form:

ABC(ABC const & abc);

and then invoke it from the derived copy-constructor as:

ConcreteDerivedClass(ConcreteDerivedClass const & obj): ABC( obj)
                                        //^^^^^ make it const

Here, ABC(obj) calls the base class copy-constructor, passing obj as reference.

Note that you're privately inhereting from ABC.

class ConcreteDerivedClass: private ABC

I think what you need is called public inheritance:

class ConcreteDerivedClass: public ABC

Search for private inheritance and public inheritance to know the difference between them. You will find numerous topics on this site. :-)

于 2012-08-26T14:25:36.533 回答
2

你不能,因为编译器会为你生成一个默认的复制构造函数。然而,你的例子并没有错。您从派生类中调用的不是复制构造函数。

于 2012-08-26T14:33:35.937 回答
1

据此,必须是一个参考。

于 2012-08-26T14:26:52.410 回答