473,385 Members | 1,742 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

"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 3445
* 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
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();...
12
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...
6
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:...
175
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...
4
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? -- ...
19
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...
8
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...
4
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...
7
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...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

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.