473,466 Members | 1,370 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

What is the correct way to derive a class in regard to overloaded operators

Hi,

I am trying to derive a new class that will add new functions but no
new data members and the base class has overloaded operators
(+,-,+=,-=,etc...) returning either (Base &) or (const Base) depending
on the operator:

class Derived : public Base
{
};

The problem occurs if I do the following

Derived d1,d2;
Derived d3 = d1+d2;

what should be the better approach?

Just add
Derived(const Base&) and
Derived &operator=(const Base&)

or should it be better to redeclare all the operators (there is a lot
of them) in the derived class and perform nothing except calling the
base class version and return Derived reference or object.

Greetings,
Olivier Langlois
http://www3.sympatico.ca/olanglois
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

May 19 '06 #1
13 1975
ol*******@sympatico.ca wrote:
I am trying to derive a new class that will add new functions but no
new data members and the base class has overloaded operators
(+,-,+=,-=,etc...) returning either (Base &) or (const Base) depending
on the operator:

class Derived : public Base
{
};

The problem occurs if I do the following

Derived d1,d2;
Derived d3 = d1+d2;

what should be the better approach?

Just add
Derived(const Base&) and
Derived &operator=(const Base&)
If 'Derived' never has to know that addition, etc., is being performed,
then yes, it should be sufficient.
or should it be better to redeclare all the operators (there is a lot
of them) in the derived class and perform nothing except calling the
base class version and return Derived reference or object.


I don't think how it could help _unless_ you're foreseeing the need for
'Derived' to amend the operation somehow in the future (even if it does
not need it now). Introduction of an interface should be done sooner
rather than later.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
May 19 '06 #2

ol*******@sympatico.ca wrote:
Hi,

I am trying to derive a new class that will add new functions but no
new data members and the base class has overloaded operators
(+,-,+=,-=,etc...) returning either (Base &) or (const Base) depending
on the operator:

class Derived : public Base
{
};

The problem occurs if I do the following

Derived d1,d2;
Derived d3 = d1+d2;

what should be the better approach?

Just add
Derived(const Base&) and
Derived &operator=(const Base&)

or should it be better to redeclare all the operators (there is a lot
of them) in the derived class and perform nothing except calling the
base class version and return Derived reference or object.


IMO Always overload the operators for the derived versions if you can,
otherwise each operation is effectively losing type information and
possibly the deriveds extra data. In fact dont bother overloading them
for the base class so you get an error if you havent. Of course thats
more work... so you could try looking at ;

http://www.boost.org/libs/utility/operators.htm

which is meant to reduce the work required to implement common
operators.
(No I havent used it myself)

regards
Andy Little
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

May 21 '06 #3
In article <11*********************@j55g2000cwa.googlegroups. com>,
ol*******@sympatico.ca writes
Hi,

I am trying to derive a new class that will add new functions but no
new data members and the base class has overloaded operators
(+,-,+=,-=,etc...) returning either (Base &) or (const Base) depending
on the operator:

class Derived : public Base
{
};

The problem occurs if I do the following

Derived d1,d2;
Derived d3 = d1+d2;

what should be the better approach?


You almost certainly do not want to do this by public derivation as I
very much doubt that Base was designed as a base class (i.e. I expect it
to lack a virtual dtor)

Why do you want a class that is identical to Base other than for some
added functionality? Why not just add some free functions? Your derived
class will have no special access to the base class so its member
functions cannot do anything that free functions could not do.

Before I give you any further guidance I need to know why you want to do
what you are doing.
--
Francis Glassborow ACCU
Author of 'You Can Do It!' see http://www.spellen.org/youcandoit
For project ideas and contributions: http://www.spellen.org/youcandoit/projects
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

May 21 '06 #4

On 19 May 2006 06:13:44 -0400, ol*******@sympatico.ca wrote:
Hi,

I am trying to derive a new class that will add new functions but no
new data members and the base class has overloaded operators
(+,-,+=,-=,etc...) returning either (Base &) or (const Base) depending
on the operator:

class Derived : public Base
{
};

The problem occurs if I do the following

Derived d1,d2;
Derived d3 = d1+d2;

what should be the better approach?

Just add
Derived(const Base&) and
Derived &operator=(const Base&)

or should it be better to redeclare all the operators (there is a lot
of them) in the derived class and perform nothing except calling the
base class version and return Derived reference or object.


Sounds like a bit of a design problem to me. What control do you have
over the design of your Base class?

Any operators or other functions which return a Base object will be a
potential problem WRT slicing.

--
Bob Hairgrove
No**********@Home.com
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

May 21 '06 #5
Francis Glassborow wrote:
In article <11*********************@j55g2000cwa.googlegroups. com>,
ol*******@sympatico.ca writes
I am trying to derive a new class that will add new functions
but no new data members and the base class has overloaded
operators (+,-,+=,-=,etc...) returning either (Base &) or
(const Base) depending on the operator: class Derived : public Base
{
}; The problem occurs if I do the following Derived d1,d2;
Derived d3 = d1+d2; what should be the better approach?

You almost certainly do not want to do this by public
derivation as I very much doubt that Base was designed as a
base class (i.e. I expect it to lack a virtual dtor) Why do you want a class that is identical to Base other than
for some added functionality? Why not just add some free
functions? Your derived class will have no special access to
the base class so its member functions cannot do anything that
free functions could not do.


Good point. I just automatically assumed that one of his goals
was to have a new type, which of course supposes a class, but
if that's not the case, free functions are the way to go.

There is also one very special case I've used from time to time:
derivation to provide new constructors. But in such cases,
"slicing" is perfectly acceptable -- once the constructor has
run, I simply use the object as if it were a base, copying the
base part, etc. without worrying that the class was originally
constructed as a derived.

--
James Kanze ka*********@neuf.fr
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France +33 (0)1 30 23 00 34

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

May 22 '06 #6
ol*******@sympatico.ca wrote:
I am trying to derive a new class that will add new functions
but no new data members and the base class has overloaded
operators (+,-,+=,-=,etc...) returning either (Base &) or
(const Base) depending on the operator: class Derived : public Base
{
};
I'm not sure what you're doing is a good idea. Operator
overloading largely depends on value semantics, where as
derivation practically requires reference semantics to work
correctly.
The problem occurs if I do the following Derived d1,d2;
Derived d3 = d1+d2; what should be the better approach? Just add
Derived(const Base&) and
Derived &operator=(const Base&) or should it be better to redeclare all the operators (there
is a lot of them) in the derived class and perform nothing
except calling the base class version and return Derived
reference or object.


I'm not sure why you are deriving, so it's hard to say, but I
suspect that the cleanest approch would use containment, not
inheritance, and redefine every operator. It's a lot of copy
work, of course, but one way or the other, I don't see any way
around it.

--
James Kanze ka*********@neuf.fr
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France +33 (0)1 30 23 00 34

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

May 22 '06 #7
> You almost certainly do not want to do this by public derivation as I
very much doubt that Base was designed as a base class (i.e. I expect it
to lack a virtual dtor)

Why do you want a class that is identical to Base other than for some
added functionality? Why not just add some free functions? Your derived
class will have no special access to the base class so its member
functions cannot do anything that free functions could not do.

Before I give you any further guidance I need to know why you want to do
what you are doing.


Both Base and Derived are probably meant to be used as value types that are
allocated on the stack (hence no need for a virtual destructor). Base class
might wrap an integral type to a class and define operations so that it
could be used in place of the native integer type and Derived might
public-inherit from Base and extend its functionality by adding a support
for serialization, etc. The question of reimplementing operations in Derived
is pretty reasonable in this context then.

As for the original question... I am afraid that all operations have to be
reimplemented in Derived as stubs delegating the calls to Base, because
Derived's operator+() should really return Derived, for example.

-- Marek


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

May 23 '06 #8
ol*******@sympatico.ca writes:
Hi,

I am trying to derive a new class that will add new functions but no
new data members and the base class has overloaded operators
(+,-,+=,-=,etc...) returning either (Base &) or (const Base) depending
on the operator:

class Derived : public Base
{
};

The problem occurs if I do the following

Derived d1,d2;
Derived d3 = d1+d2;

what should be the better approach?

Just add
Derived(const Base&) and
Derived &operator=(const Base&)

or should it be better to redeclare all the operators (there is a lot
of them) in the derived class and perform nothing except calling the
base class version and return Derived reference or object.


if you can change the code you of Base and want to create a few
different Derived class, you probably want to have your base class be
a template parametered by your derived class:

template <typename T>
class Base {
T& operator+(T&);
// ...
};

class Derived : public Base<Derived> {
// ...
};

--
Philippe Amarenco, aka Phix
epita 2007 - GISTR - LSE - EpX

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

May 23 '06 #9
Hi,

Thanks all for your input. I am going to answer to your questions to
keep the ball rolling.

I have 100% control over the base class and I'm willing to change
anything to come up with the best solution. Here is some background on
what I try to achieve. I have class with a default constructor defined
like this:

Base( int param = DEFAULTVAL);

I have reused that class in a new program where I would like to
override DEFAULTVALUE to something else when I create arrays of this
class so the way I came up to solve this problem is by doing this:

templace<int DEFAULT = DEFAULTVAL>
class Derived : public Base
{
Derived( int param = DEFAULT );
};

I did not changed Base to become a template because only object
construction needs to be templatized.

However by doing so, I introduced a new problem with Base operators.
Since my original post, for now, to solve the problem is this:

1- Made Base abstract
2- Keep operators returning references in Base and move operators
returning objects to Derived.
3- Added the constructor Derived( const Base &) Derived( const
Derived&) (By experience, I found out that I needed both)
4- Added the assignment opertor=(const Base &) (otherwise a temporary
Derived object is created...)

Thanks for your help!
Greetings,
Olivier Langlois
http://www3.sympatico.ca/olanglois
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

May 23 '06 #10
In article <e4***********@ns.felk.cvut.cz>, Marek Vondrak
<no**@none.com> writes
Both Base and Derived are probably meant to be used as value types that are
allocated on the stack (hence no need for a virtual destructor). Base class
might wrap an integral type to a class and define operations so that it
could be used in place of the native integer type and Derived might
public-inherit from Base and extend its functionality by adding a support
for serialization, etc. The question of reimplementing operations in Derived
is pretty reasonable in this context then.


In the circles I move in, public inheritance of a value type is
considered suspect. Public inheritance represents an 'is-a' relationship
with the concept of LSP.

If the derived type is intended to be a full value type the risk of
slicing (i.e unintentional conversion to the base type) provides an
opportunity for subtle bugs.

Of course what we really need is strong typedefs such as those being
considered for C++0x where issues of convertability are tackled by the
form of the typedef.

--
Francis Glassborow ACCU
Author of 'You Can Do It!' see http://www.spellen.org/youcandoit
For project ideas and contributions: http://www.spellen.org/youcandoit/projects
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

May 23 '06 #11
ol*******@sympatico.ca wrote:
I have 100% control over the base class and I'm willing to
change anything to come up with the best solution. Here is
some background on what I try to achieve. I have class with a
default constructor defined like this: Base( int param = DEFAULTVAL); I have reused that class in a new program where I would like
to override DEFAULTVALUE to something else
That's trivial... Just do it, and don't worry about the slicing.
The Base operators will still take a Derived, and you should use
Base just about everywhere except when you need to construct.
(Definitions like:
Base obj = Derived() ;
are perfectly legal.)
when I create arrays of this class
As long as the arrays are std::vector, no problem. A C style
array, on the other hand, might be.
so the way I came up to solve this problem is by doing this: templace<int DEFAULT = DEFAULTVAL>
class Derived : public Base
{
Derived( int param = DEFAULT );
}; I did not changed Base to become a template because only
object construction needs to be templatized. However by doing so, I introduced a new problem with Base
operators. Since my original post, for now, to solve the
problem is this: 1- Made Base abstract
I'm not sure what this buys you.
2- Keep operators returning references in Base and move operators
returning objects to Derived.
3- Added the constructor Derived( const Base &) Derived( const
Derived&) (By experience, I found out that I needed both)
The compiler should provide the second, if you don't.
4- Added the assignment opertor=(const Base &) (otherwise a
temporary Derived object is created...)


You also need to make the destructor of Base virtual. I'd also
add a private operator new[] to Derived -- in no case can you
allow the construction of C style arrays of Derived on the heap
(since they will fatally end up assigned to a Base*).

--
James Kanze GABI Software
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

May 25 '06 #12
kanze wrote:
ol*******@sympatico.ca wrote:

[snip]
4- Added the assignment opertor=(const Base &) (otherwise a
temporary Derived object is created...)


You also need to make the destructor of Base virtual. I'd also
add a private operator new[] to Derived -- in no case can you
allow the construction of C style arrays of Derived on the heap
(since they will fatally end up assigned to a Base*).


Yeah, but...

if sizeof(Base)==sizeof(Derived), and if ~Derived() has an empty
body (i.e. it does nothing but call ~Base()), then there isn't
likely to be a problem, not even with new Derived[] -- is there?
Yes, I am aware that it violates the standard... but show me a
program that does this, and a compiler that makes it crash?

#include <iostream>
#include <ostream>

struct Base {
int x;
// whatever...
Base(int z=0) : x(z) {}
~Base() { std::cout << "Destroy: " << x << '\n'; }
};

struct Derived : public Base { // No Multiple Inheritance
static int nextX;
Derived() : Base(nextX++) {}
// No new non-static data members
//~Derived(); -- Does not explicitly define the destructor
};
int Derived::nextX = 100;

int main() {
{
Base a(10);
Base *b = new Derived[5];

delete[] b; // Deleting with wrong data type, violates
standard...
// but is it EVER a problem in these limited situations?
// Calls ~Base() directly, instead of going through
~Derived()...
// But all ~Derived() does is forward to ~Base(), right?
}

std::cout << "Fin" << std::endl;
}

Even Comeau doesn't complain about this code
(haven't tried running it with Comeau, though)
I did try it with Microsoft, it gave the obvious results.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

May 26 '06 #13
Allan W wrote:
kanze wrote:
ol*******@sympatico.ca wrote: [snip]
4- Added the assignment opertor=(const Base &) (otherwise a
temporary Derived object is created...)

You also need to make the destructor of Base virtual. I'd
also add a private operator new[] to Derived -- in no case
can you allow the construction of C style arrays of Derived
on the heap (since they will fatally end up assigned to a
Base*).

Yeah, but... if sizeof(Base)==sizeof(Derived), and if ~Derived() has an
empty body (i.e. it does nothing but call ~Base()), then there
isn't likely to be a problem, not even with new Derived[] --
is there? Yes, I am aware that it violates the standard...
but show me a program that does this, and a compiler that
makes it crash?
In the absense of further derivation, I think in fact it is
safe. I even once toyed with the idea making a proposal to the
standard to guarantee that it work -- basically, defining
"trivial derivation" as adding new constructors and nothing
else, and then saying that it would work in the case of trivial
derivation. In the end, it seemed too much bother, and too much
special case. And not really that useful.
#include <iostream>
#include <ostream> struct Base {
int x;
// whatever...
Base(int z=0) : x(z) {}
~Base() { std::cout << "Destroy: " << x << '\n'; }
}; struct Derived : public Base { // No Multiple Inheritance
static int nextX;
Derived() : Base(nextX++) {}
// No new non-static data members
//~Derived(); -- Does not explicitly define the destructor
};
int Derived::nextX = 100; int main() {
{
Base a(10);
Base *b = new Derived[5]; delete[] b; // Deleting with wrong data type, violates
standard...
// but is it EVER a problem in these limited situations?
// Calls ~Base() directly, instead of going through
~Derived()...
// But all ~Derived() does is forward to ~Base(), right?
} std::cout << "Fin" << std::endl;
} Even Comeau doesn't complain about this code
(haven't tried running it with Comeau, though)
I did try it with Microsoft, it gave the obvious results.


Well, it's undefined behavior, and I doubt you'll find a
compiler which complains. But because it's undefined behavior,
the fact that a compiler gives the obvious results once doesn't
prove anything. (In theory, at least. In practice, knowing how
compilers work, I can't imagine an implementation where it would
fail.)

--
James Kanze ka*********@neuf.fr
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France +33 (0)1 30 23 00 34

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

May 27 '06 #14

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

Similar topics

70
by: Roy Yao | last post by:
Does it mean "(sizeof(int))* (p)" or "sizeof( (int)(*p) )" ? According to my analysis, operator sizeof, (type) and * have the same precedence, and they combine from right to left. Then this...
9
by: John Cho | last post by:
// CHO, JOHN #include<iostream> class fracpri{ int whole; int numer; int denom;
11
by: Micha | last post by:
Hello there, I think I've run into some classic c++ pitfall and maybe some of you guys can help me out. For my project I will need to use matrices and vectors and so I decided to implement them...
7
by: Riku Jarvinen | last post by:
Hello everyone, I have a logging class which writes program outputs to the logfile. The class works fine as long as only C++ native data types are considered. The problem is that I have a...
4
by: Nitin Bhardwaj | last post by:
Hello all, I am puzzled by the term 'semantics' ! Well I know about 'syntax of a language' - as defined by its associated grammar Then what is this semantics? What does the C Compiler checks...
13
by: Jason Huang | last post by:
Hi, Would someone explain the following coding more detail for me? What's the ( ) for? CurrentText = (TextBox)e.Item.Cells.Controls; Thanks. Jason
2
by: Armond VanHeusen | last post by:
A quick question if I may (this relates to .NET1.1 by the way): If I have a C# class defined in my project that does operator overloading, can I use this in my VB code? For example, I have a...
7
by: Simon Elliott | last post by:
What operators can be used to extend an enum? Can I extend an enum with an operator= and if so what's the syntax? -- Simon Elliott http://www.ctsn.co.uk
4
by: Bengan | last post by:
Hi! Where can you see if a class has overloaded operator(like +,-) in Microsofts NET class library on the net? They list members, properties, fields and other stuff for a class but no...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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,...
0
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...
0
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,...
0
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...
0
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...
0
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 ...

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.