473,670 Members | 2,618 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Virtual Constructor and Covariant Return Types

Hello,

Here is some program with virtual constructors.

Is there any difference between
* clone1() vs. clone2()
* create1() vs. create2() ?

It seems that it should be.

The program has been successfully compiled and invocated.

------ C++ code : BEGIN ------
class Shape
{
public:
virtual ~Shape() {}

virtual void draw() = 0;

virtual Shape* clone1() const = 0;
virtual Shape* create1() const = 0;

virtual Shape* clone2() const = 0;
virtual Shape* create2() const = 0;

};

class Circle : public Shape
{
public:
void draw() {}

// --- Covariant Return Types ---
Circle* clone1() const { return new Circle(*this); }
Circle* create1() const { return new Circle();}
// ------------------------------

// --- NonCovariant Return Types ---
Shape* clone2() const { return new Circle(*this); }
Shape* create2() const { return new Circle();}
// ---------------------------------

};

void userCode(Shape& s)
{
Shape* sclone1 = s.clone1();
Shape* screate1 = s.create1();

Shape* sclone2 = s.clone2();
Shape* screate2 = s.create2();
sclone1->draw();
screate1->draw();

sclone2->draw();
screate2->draw();

delete sclone1;
delete screate1;

delete sclone2;
delete screate2;

}

int main()
{
Shape* s = new Circle;
userCode (*s);

delete s;

return 0;
}
------ C++ code : END --------

--
Alex Vinokur
mailto:al****@c onnect.to
http://mathforum.org/library/view/10978.html

Jul 22 '05 #1
7 2147
Alex Vinokur wrote:
Here is some program with virtual constructors.

Is there any difference between
* clone1() vs. clone2()
* create1() vs. create2() ?
[...]
// --- Covariant Return Types ---
Circle* clone1() const { return new Circle(*this); }
Circle* create1() const { return new Circle();}
// ------------------------------

// --- NonCovariant Return Types ---
Shape* clone2() const { return new Circle(*this); }
Shape* create2() const { return new Circle();}
// ---------------------------------


[...]

Sorry, am I missing the point? You can see the what the difference is.

--
Regards,
Buster.
Jul 22 '05 #2
* "Alex Vinokur" <al****@big.foo t.com> schriebt:
Here is some program with virtual constructors.
Would be nice if people stopped using that term, even though it is
in the FAQ... ;-)
Is there any difference between
* clone1() vs. clone2()
* create1() vs. create2() ?

class Circle : public Shape
{
public:
void draw() {}

// --- Covariant Return Types ---
Circle* clone1() const { return new Circle(*this); }
Circle* create1() const { return new Circle();}
// ------------------------------

// --- NonCovariant Return Types ---
Shape* clone2() const { return new Circle(*this); }
Shape* create2() const { return new Circle();}
// ---------------------------------

};


The difference is not in what they do, but in the static type-checking
available for client code.

Btw. it's a good idea to indicate deallocation responsibility in some
way, e.g. by returning smart-pointers instead of raw pointers.

--
A: Because it messes up the order in which people normally read text.
Q: Why is top-posting such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 22 '05 #3
Alex Vinokur wrote:

Hello,

Here is some program with virtual constructors.

Is there any difference between
* clone1() vs. clone2()
* create1() vs. create2() ?

It seems that it should be.


No. Semantically they are equivalent.
Covariant return types are just a compile time
only thing. The created object is of type Circle
and thus both functions return a Circle*. Even
if in one of them the Circle* is called Shape*
The thing with covariant return types is this:
sometimes you call the virtual function and you know
exactly what the returned pointer must be.
Example:

Circle A;

Circle* B = A.clone();

The thing returned from A.clone() must be Circle* since A is a Circle.
It can't be anything else. Yet you are forced (without covariant
return types) to use a cast:

Circle* B = dynamic_cast< Circle* >( A.clone() );

or to make B a different type:

Shape* B = Circle.clone();

because the return value in the clone() function in the base class,
specified Shape* as return value.

This is where covariant return types help: If you (and the
compiler) know exactly which one of the derived class pointer
is returned, you can use it directly without going though the hassle
of casting.

--
Karl Heinz Buchegger
kb******@gascad .at
Jul 22 '05 #4

"Buster" <no***@nowhere. com> wrote in message news:c5******** **@newsg3.svr.p ol.co.uk...
Alex Vinokur wrote:
Here is some program with virtual constructors.

Is there any difference between
* clone1() vs. clone2()
* create1() vs. create2() ?


[...]
// --- Covariant Return Types ---
Circle* clone1() const { return new Circle(*this); }
Circle* create1() const { return new Circle();}
// ------------------------------

// --- NonCovariant Return Types ---
Shape* clone2() const { return new Circle(*this); }
Shape* create2() const { return new Circle();}
// ---------------------------------


[...]

Sorry, am I missing the point? You can see the what the difference is.


clone1() and create1() return Circle*,
clone2() and create2() return Shape*.

The question is if we can use
* create2() instead of create1(),
* clone2() instead of clone1()
with the same results.

--
Alex Vinokur
mailto:al****@c onnect.to
http://mathforum.org/library/view/10978.html

Jul 22 '05 #5


Alex Vinokur wrote:
Sorry, am I missing the point? You can see the what the difference is.
clone1() and create1() return Circle*,
clone2() and create2() return Shape*.


Exactly that.
The question is if we can use
* create2() instead of create1(),
* clone2() instead of clone1()
with the same results.


Yes.

Circle c;
Circle * p = static_cast <Circle *> (c.create2 ());
Circle * q = static_cast <Circle *> (c.clone2 ());

You should probably declare the "create" functions static and the
constructors private or protected.

--
Regards,
Buster.
Jul 22 '05 #6


Karl Heinz Buchegger wrote:
Alex Vinokur wrote: The thing returned from A.clone() must be Circle* since A is a Circle.
It can't be anything else. Yet you are forced (without covariant
return types) to use a cast:

Circle* B = dynamic_cast< Circle* >( A.clone() );


static_cast is sufficient, since we already know the dynamic type.
dynamic_cast is for querying the type.

--
Regards,
Buster.
Jul 22 '05 #7
Buster wrote:

Karl Heinz Buchegger wrote:
Alex Vinokur wrote:

The thing returned from A.clone() must be Circle* since A is a Circle.
It can't be anything else. Yet you are forced (without covariant
return types) to use a cast:

Circle* B = dynamic_cast< Circle* >( A.clone() );


static_cast is sufficient, since we already know the dynamic type.
dynamic_cast is for querying the type.


Ah. yes.
--
Karl Heinz Buchegger
kb******@gascad .at
Jul 22 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
3890
by: Aryeh M. Friedman | last post by:
If I have something like this: class NumberException { }; class Number { public: ... virtual unsigned long getValue() {throw(NumberException);}; ...
14
1998
by: Stefan Slapeta | last post by:
Hi, this code does not compile in C#: class base_class {} class derived_class : base_class {} class A { public virtual base_class f()
2
2511
by: Edward Diener | last post by:
In C++ an overridden virtual function in a derived class must have the exact same signature of the function which is overridden in the base class, except for the return type which may return a pointer or reference to a derived type of the base class's return type. In .NET the overridden virtual function is similar, but an actual parameter of the function can be a derived reference from the base class's reference also. This dichotomy...
6
2548
by: miked | last post by:
Why are there still no covariant return types? All searches reveal no workarounds accept for using an interface which is a real pain. I wind up missing this capability almost every time I inherit a class. The best workaround and one that I use is the new keyword and cast the base class reference, but in my opinion this is a bad practice leading to error prone code. Can someone from MS chime in on this and provide some feedback?
8
2175
by: Alex Vinokur | last post by:
Here is a code from http://www.parashift.com/c++-faq-lite/virtual-functions.html#faq-20.8 -------------------------------------- class Shape { public: virtual ~Shape() { } // A virtual destructor virtual void draw() = 0; // A pure virtual function virtual void move() = 0; ...
3
4547
by: kikazaru | last post by:
Is it possible to return covariant types for virtual methods inherited from a base class using virtual inheritance? I've constructed an example below, which has the following structure: Shape = base class Triangle, Square = classes derived from Shape Prism = class derived from Shape TriangularPrism, SquarePrism = classes derived from Triangle and Prism, or Square and Prism respectively
1
3466
by: Bart Simpson | last post by:
Can anyone explain the concept of "slicing" with respect to the "virtual constructor" idiom as explain at parashift ? From parashift: class Shape { public: virtual ~Shape() { } // A virtual destructor
4
1623
by: Rahul | last post by:
Hi Everyone, I understand that the constructors can't be virtual and parashift has the following example, to have an workaround for the constructors to be virtual, class Shape { public: virtual ~Shape() { } // A virtual destructor virtual void draw() = 0; // A pure virtual function
1
2082
by: mosfet | last post by:
Hi, I am trying to modify existing code to use smart pointers and I get some issues with virtual methods : class Folder : public Object { public: friend class PimItemCollection; friend class ContactCollection;
0
8386
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8901
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8814
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7415
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5683
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4209
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4390
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2041
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1792
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.