`

c++ - c++ exception to return type match and virtually virtual new operator

    博客分类:
  • c++
c++ 
阅读更多

How do we duplicate a object through its pointer or reference? suppose 

 

NotQuery *pnq;

NotQuery *pnq2 = new NotQuery(*pnq);

 

 

however, what if we have this ?

 

 

const Query *pq = pnq->op();

// ???

 

 

we cannot dclare a virutal new instance of operator new, the new operator is a static member, and it applies before the constructor. 

 

THINK:??? you can overload new operator inside the class, , however, we cannot make it virtual still it does not answer the time/order problem.

 

the solution is a surrogate, somehting like this:

 

 

public Query {
public:
   virtual Query * clone() = 0;
};
 

 

however, if we cannot change the return type in the derived class, then we might see this

 

 

NameQuery *png = new NameQuery("Rike");
NameQuery *pnq2 = static_cast<NameQuery*> (pnq->clone());

 

BUT!!!,there is an exception to that "requirement that return type of the derived class must match exactly that of the base class".

 

 

so, in the derived class, you can write 

 

public NameQuery : public Query 
{
public:
  virtual NameQuery* clone() { return new NameQuery(*this); }
};

 

 

Below shows the whole code ::

 

class Base 
{
public :
	Base() { }
	Base(Base &base) {}
	virtual Base *clone();
protected:
	Base *print();
private:

};

class Derived : public Base {
public:
	Derived() {}
	Derived (Derived &derived) : Base(derived) {} 
	virtual Derived *clone();
protected:
	Base *print();

};

Base* Base::clone(){ 
	return new Base(*this);
}

Derived* Derived::clone() {
	return new Derived(*this);
}
 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics