473,763 Members | 3,712 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

"Virtual constructor" and slicing

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
virtual void draw() = 0; // A pure virtual function
virtual void move() = 0;
...
virtual Shape* clone() const = 0; // Uses the copy constructor
virtual Shape* create() const = 0; // Uses the default constructor
};

class Circle : public Shape {
public:
Circle* clone() const; // Covariant Return Types; see below
Circle* create() const; // Covariant Return Types; see below
...
};

Circle* Circle::clone() const { return new Circle(*this); }
Circle* Circle::create( ) const { return new Circle(); }

In the clone() member function, the new Circle(*this) code calls
Circle's copy constructor to copy the state of this into the newly
created Circle object. (Note: unless Circle is known to be final (AKA a
leaf), you can reduce the chance of slicing by making its copy
constructor protected.) In the create() member function, the new
Circle() code calls Circle's default constructor.

May 23 '07 #1
1 3474
* Bart Simpson:
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
virtual void draw() = 0; // A pure virtual function
virtual void move() = 0;
...
virtual Shape* clone() const = 0; // Uses the copy constructor
virtual Shape* create() const = 0; // Uses the default constructor
};

class Circle : public Shape {
public:
Circle* clone() const; // Covariant Return Types; see below
Circle* create() const; // Covariant Return Types; see below
...
};

Circle* Circle::clone() const { return new Circle(*this); }
Circle* Circle::create( ) const { return new Circle(); }

In the clone() member function, the new Circle(*this) code calls
Circle's copy constructor to copy the state of this into the newly
created Circle object. (Note: unless Circle is known to be final (AKA a
leaf), you can reduce the chance of slicing by making its copy
constructor protected.) In the create() member function, the new
Circle() code calls Circle's default constructor.
Slicing is when only the (or more precisely, a) base class part of an
object is copied.

It can happen with clone() and, interpreting the word slicing very
liberally, with create() when the functions aren't properly overridden
and reimplemented in a derived class.

Mostly that's boilerplate code that could in principle be generated
automatically, and in practice you can do that via macros (if you're not
afraid of name collisions and other issues with macros). But as far as
I know nobody's found of way of ensuring at compile time that a class
does override a concrete member function, and in turn imposes that
requirement on its derived classes. Or even without the latter feature.

However, while you can't (AFAIK) detect at compile time or run time
whether the proper clone() function is called, you can detect at run
time that it's a wrong one, e.g.

Circle* clone() const
{
if( typeid( *this ) != typeid( Circle ) ) { throw "Urgh"; }
return new Circle( *this );
}

It's better than nothing, but both the cloning business and e.g. the
visitor pattern shows that there is most likely a very basic and general
language feature missing, something that does away with manually
replicating boilerplate code in the classes.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
May 23 '07 #2

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

Similar topics

4
2424
by: Alex Vinokur | last post by:
http://www.parashift.com/c++-faq-lite/virtual-functions.html#faq-20.6 Faq-20.6 contains function userCode(Shape&) : void userCode(Shape& s) { Shape* s2 = s.clone(); Shape* s3 = s.create(); ... // stuff; for instance
12
13467
by: cppaddict | last post by:
Hi, I know that it is illegal in C++ to have a static pure virtual method, but it seems something like this would be useful when the following 2 conditions hold: 1. You know that every one of your Derived classes will need to implement some method, but implement it differently, and that the base class cannot implement it. This is where pure virtual comes in.
6
9769
by: kelvSYC | last post by:
This little bit of seeminly innocent code seems to give me these two errors, all on the line that declares check(). Is there some part of C++ that I'm missing out on? class Condition { public: Condition() {} virtual ~Condition() {} virtual bool check() const;
175
8896
by: Ken Brady | last post by:
I'm on a team building some class libraries to be used by many other projects. Some members of our team insist that "All public methods should be virtual" just in case "anything needs to be changed". This is very much against my instincts. Can anyone offer some solid design guidelines for me? Thanks in advance....
4
8507
by: Jon Shemitz | last post by:
Syntax seems to say "modifiers is modifiers" and either is valid, but Google searches seem to show that "public virtual" is more common. Is there any sort of (semi) official convention? -- programmer, author http://www.midnightbeach.com and father http://www.midnightbeach.com/hs
19
3580
by: Martin Oddman | last post by:
Hi, I have a compiling problem. Please take a look at the code below. I have an application that is built upon three tiers: one data tier (Foo.DataManager), one business tier (Foo.Kernel) and one web presentation tier (Foo.WebFiles). The data tier shall only be accessible thru the business tier so I do NOT want a reference to the data tier in the presentation tier. In the business tier I have a class with the name CategoryItem that...
8
4045
by: Asfand Yar Qazi | last post by:
Hi, I have the following header file in my 'everything useful I think of in one place' library: ============= BEGIN CODE SNIPPET =========== /** All classes that derive from this obtain a 'virtual constructor' - ie if the 'clone()' method is called on a polymorphic type, an object of the same (unknown) type is returned. */
4
1774
by: mwebel | last post by:
Hi, i have a StuffProducer(SProd) and a StuffContainer(SCont) basis class. -SProd produces values, that are stored in SCont. -Derived classes of both are compatible only on the same derivated path.(SProdA with SContA, SProdB with SContB and so on ). SProd should have always a intance of its respective Container as a private variable.
7
2479
by: desktop | last post by:
This page: http://www.eptacom.net/pubblicazioni/pub_eng/mdisp.html start with the line: "Virtual functions allow polymorphism on a single argument". What does that exactly mean? I guess it has nothing to do with making multiple arguments in a declaration like:
0
9563
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10145
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
9998
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
8822
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
6642
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
5270
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
5406
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3917
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3523
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.