What is wrong with this inheritance? - c++

I just don't get it. Tried on VC++ 2008 and G++ 4.3.2
#include <map>
class A : public std::multimap<int, bool>
{
public:
size_type erase(int k, bool v)
{
return erase(k); // <- this fails; had to change to __super::erase(k)
}
};
int main()
{
A a;
a.erase(0, false);
a.erase(0); // <- fails. can't find base class' function?!
return 0;
}

When you declare a function in a class with the same name but different signature from a superclass, then the name resolution rules state that the compiler should stop looking for the function you are trying to call once it finds the first match. After finding the function by name, then it applies the overload resolution rules.
So what is happening is the compiler finds your implementation of erase(int, bool) when you call erase(0), and then decides that the arguments don't match.

1: You need to be extremely careful when deriving from C++ standard library containers. It can be done, but because they don't have virtual destructors and other such niceties, it is usually the wrong approach.
2: Overload rules are a bit quirky here. The compiler first looks in the derived class, and if it finds any overload with the same name, it stops looking there. It only looks in the base class if no overloads were found in the derived class.
A simple solution to that is to introduce the functions you need from the base class into the derived class' namespace:
class A : public std::multimap<int, bool>
{
public:
using std::multimap<int, bool>::erase; // Any erase function found in the base class should be injected into the derived class namespace as well
size_type erase(int k, bool v)
{
return erase(k);
}
};
Alternatively, of course, you could simply write a small helper function in the derived class redirecting to the base class function

You've hidden the base class's erase member function by defining a function in the derived class with the same name but different arguments.
http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.9

First of all, you should never derive from STL containers, because no STL containers define a virtual destructor.
Second of all, see Greg's answer about inheritance.

Think whether you really want to inherit from std::map. In all the time I've written code, and that's longer than STL exists, I've never seen an instance where inheriting from a std::container was the best solution.
Specifically, ask yourself whether your class IS a multimap or HAS a multimap.

Others have answered how to resolve the syntax problem and why it can be dangerous to derive from standard classes, but it's also worth pointing out:
Prefer composition to inheritance.
I doubt you mean for 'A' to explicitly have the "is-a" relationship to multimap< int, bool >. C++ Coding Standards by Sutter/Alexandrescu has entire chapter on this (#34), and Google points to many good references on the subject.
It appears there is a SO thread on the topic as well.

For those that use Effective C++ as a C++ programming reference, this issue is covered in Item 33 (Avoid hiding inherited names.) in the book.

I agree with others' comments that you need to be very careful inheriting from STL classes, and it should almost always be avoided.
However, this problem could arise with some other base class from which it's perfectly sensible to inherit.
My question is: why not give your 2-argument function a different name? If it takes different arguments, presumably it has a slightly different meaning? E.g. erase_if_true or erase_and_delete or whatever the bool means.

To replace __super in a portable way, define a typedef at the top of your class like this:
typedef std::multimap<int, bool> parent;
public:
size_type erase(int k, bool v)
{
return parent::erase(k);
}
It does not need to be "parent" of course. It could be any name you like, as long as it is used consistently throughout your project.

Related

Does Scott Meyers's advice to prefer non-member non-friend methods apply to object construction?

Let's say I have a class:
class C{
int x_;
int y_;
public:
C(int x, int y): x_(x), y_(y){}
};
Then I want to add construction from a string, which would just parse x and y. Before reading Meyers's book I would usually make it another constructor in class C. However, it's also possible to make it non-member non-friend:
C CFromString(const std::string& s){
int x, y;
//...parse them somehow, throw exception if needed...
return C(x,y);
}
To me this is standard situation for many "value classes", when there is a "main" constructor which sets private members to provided values (probably checking there correctness). Other constructors for such classes are often just calculate these values from some other arguments.
Are there any drawbacks in making such constructors non-member non-friends like in my example?
Upd. I understand the Meyers's advice, and what are the advantages of NMNF functions. There is just no examples of NMNF object construction in his book, so I want to ensure that his advice applies to construction as well.
If you start adding constructors for every possible way a class can be serialized, you are tightly coupling that class with those serialization methods.
It is preferred that you separate the class and the serializer in order to separate concerns. Let the class focus on what the class does and the serializer on what it does (read json or whatever)
You have to consider that your class might be serialized from a file, from a socket, from json, from xml, from a database...from any number of things.
That's why in modern programming we use interfaces.
We also make use of the Factory pattern.
One drawback is a bit of inconsistency, which is an esthetic concern.
You're calling a CFromString constructor function rather than invoking a constructor called C. The relationship between them is arbitrary, just through the C prefix in the name.
If you make it a static member function, then you can call it C::FromString so that it belongs to the class.
If this is done all over the place in a large project, some sort of convention would help. Like say, whenever we have a class C, and a non-member constructor function for making C-s, let's always call it CCons, and then always use overloading for different types. Thus, if we have a Widget class, we then call our overloaded family WidgetCons:
Widget WidgetCons(const std::string &s) { /* make it from string */ }
Widget WidgetCons(int i) { /* make it from int */ }
and so on. If this is consistent in our 250,000 line codebase, whenever someone sees any FooCons or BarCons, they know exactly what it is.

Internal class declaration [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Pros and cons of using nested C++ classes and enumerations?
Consider the following declaration.
class A {
public:
class B{
};
};
Nothing special.
But what are the benefits of this?
What reasons may there be for putting one class inside of another?
There is no inheritance benefit between both classes.
If B is put inside of A for its private names sharing, then A is for B just a namespace, and there is reason to make B private, too.
What do you think about this?
Conceptually, it lets the programmer(s) know that class B relates specifically to class A. When you use class B outside of class A, you must use the type as A::B, which reminds you, every time, that B is related to A. This doesn't add any functionality, but shows a relationship.
Similarly, you don't have to use inheritance/composition, or classes at all. You can more or less simulate classes in C just by using structs and functions. It's just a way to keep the code cleaner and more straightforward and let the programmer relate the code to the design more easily. Classes accomplish this much more than public subclasses do, but that's just an example.
If it's a private/protected subclass (which I see it isn't in your example), then that obviously limits that class to the implementation of that class and that class's children, which might be desired (again design-wise) if the only use case of that class is in the implementation of that class (and possibly its children).
Benefit 1: The namespace aspect
Indeed, A provides a namespace for B, and this can help us structure our code much better. Consider a concrete example with vector for A, and iterator for B. Arguably,
class vector {
public:
class iterator { /*...*/ };
iterator begin() { /*...*/ }
};
is easier to type, to read, and to understand than
class vector_iterator {
/*...*/
};
class vector {
public:
vector_iterator begin() { /*...*/ }
};
Observe, in particular:
When the two classes (vector and iterator) depend on each other, i.e. use each other's members, the second version above would require one of the two to be forward-declared, and in some cases mutual type-dependencies might lead to unresolvable situations. (Using nested classes, it is much easier to avoid such problems, because within most parts of the nested class definition, the outer class is considered completely-defined. This is due to §9.2/2.)
You may very well have many other data types that maintain their own iterator, e.g. linked_list. Using the second version above, you'd need to define linked_list_iterator as a separate class. Class names would get ever longer and complicated the more of these 'dependent' types and alternative types you added.
Benefit 2: Templates
Continuing the example above, consider now a function template that takes a container (such as vector and linked_list defined above) as arguments and iterates over them:
template <typename Container>
void iterate(const Container &container) {
/*...*/
}
Inside this function, you'd obviously very much like to use the iterator type of Container. If that is a nested type, it's easy:
typename Container::iterator
But if it isn't, you would have to take the iterator type as a separate template parameter:
template <typename Container, typename Iterator>
void iterate(const Container &container) {
/*...*/
Iterator it = container.begin();
/*...*/
}
And if that iterator type does not appear among the function arguments, the compiler could not even guess the type. You'd have to explicitly add it in angle brackets each time you call the iterate function.
Final notes: None of this has much to do with whether the nested class is declared as public or private. My examples above suggest a situation in which a public nested type is clearly preferrable, because I suppose the iterator type should be able to be used outside the container class.
What reasons may be for putting one class inside of another one?
If you need to restrict the scope of B to only available for A, then internal class definition helps. Because it restricts the class scope to local.This is call scope localization.These are in more generic term called inner class declaration. Check this link.
This stackoverflow question helps you understand more.

Use of the "memberspace" idiom?

Today I learned about the C++ "memberspace" idiom, which roughly abuses a property of C++ that makes T::bar as well as T.bar work, when T is both a type and an object in some scope.
struct A {
struct Controls {
/* put some typedefs/data/functions here */
} Controls;
};
// Can be used as a type and value
A a;
A::Controls::iterator it = a.Controls.begin();
Have you ever used this idiom in practice? Have you found it useful? What's some good or the best application of the idiom?
No, I have never used that technique (and I don't think it deserves to be called an "idiom"):
Since I haven't used it, I haven't found it useful.
A good application of that technique could be to confuse other programmers.
Another application could be to write a techno-babble article about how wonderful it is for some imagined never-in-practice encountered problem, perhaps obfuscated with lots of template metaprogramming?
Dunno, best application would probably be to write an article about all those silly-rules, like you can also have a struct and a function of the same name in the same scope, as I recall, and point out how anything that those can accomplish, can be accomplished much better by staying away from the darker corners of the language. :-) Articles don't pay much in moneys but they pay in respect and are fun to write. Please write it (TIA).
Cheers & hth.,
As #Steve already said in a comment, the fact that the nested type and the instance of this type have the same name is not a central aspect of this technique. To increase encapsulation, we could even use a member function to access the instance (even though it would less look like a namespace qualification). For example, the example you gave could be rewritten as follow without any drawback (well, maybe there are, but I can't find any at the moment):
struct A
{
struct Controls
{
//typedefs/data/functions
};
const Controls & getControls() { return controls_; }
private:
Controls controls_;
};
A a;
A::Controls::iterator = a.getControls().begin();
Here is how I see memberspaces. The goal of memberspaces is to divide the naming space of a class in order to group together related typedefs and methods. The Controls class above could be defined outside of A, but it is so tightly connected to A (each A is associated with a Controls, and vice-versa, a Controls is nothing more than a view on the object A in which it is contained) that it feels "natural" to make it a member of A, and possibly also make it friend with A (if there is a need to access A's internals).
So basically memberspaces let us define one or several views on a single object, without polluting the enclosing class namespace. As noted in the article, this can be quite interesting when you want to provide several ways to iterate over an object of your class.
For example, let's assume that I am writing a class for representing C++ classes; let's call it Class. A Class has a name, and the list of all its base classes. For convenience reasons, I would like a Class to also store the list of all the classes that inherit from it (its derived classes). So I would have a code like that:
class Class
{
string name_;
list< shared_ptr< Class > > baseClasses_;
list< shared_ptr< Class > > derivedClasses_;
};
Now, I need some member functions to add/remove base classes/derived classes:
class Class
{
public:
void addBaseClass( shared_ptr< Class > base );
void removeBaseClass( shared_ptr< Class > base );
void addDerivedClass( shared_ptr< Class > derived );
void removeDerivedClass( shared_ptr< Class > derived );
private:
//... same as before
};
And sometimes, I might need to add a way to iterate over base classes and derived classes:
class Class
{
public:
typedef list< shared_ptr< Class > >::const_iterator const_iterator;
const_iterator baseClassesBegin() const;
const_iterator baseClassesEnd() const;
const_iterator derivedClassesBegin() const;
const_iterator derivedClassesEnd() const;
//...same as before
};
The amount of names we are dealing with is still manageable, but what if we want to add reverse iteration? What if we change the underlying type for storing derived classes? That would add another bunch of typedefs. Moreover, you have probably noticed that the way we provide access to begin and end iterators does not follow the standard naming, which means we can't use generic algorithms relying on it (such as Boost.Range) without additional effort.
In fact, it is obvious when looking at the member functions name that we used a prefix/suffix to logically group them, things that we try to avoid now that we have namespaces. But since we can't have namespaces in classes, we need to use a trick.
Now, using memberspaces, we encapsulate all base-related and derived-related information in their own class, which not only let us group together related data/operations, but can also reduce code duplication: since the code for manipulating base classes and derived classes is the same, we can even use a single nested class:
class Class
{
struct ClassesContainer
{
typedef list< shared_ptr< Class > > const_iterator;
ClassesContainer( list< shared_ptr< Class > > & classes )
: classes_( classes )
{}
const_iterator begin() const { return classes_.begin(); }
const_iterator end() const { return classes_.end(); }
void add( shared_ptr< Class > someClass ) { classes_.push_back( someClass ); }
void remove( shared_ptr< Class > someClass ) { classes.erase( someClass ); }
private:
list< shared_ptr< Class > > & classes_;
};
public:
typedef ClassesContainer BaseClasses;
typedef ClassesContainer DerivedClasses;
// public member for simplicity; could be accessible through a function
BaseClasses baseClasses; // constructed with baseClasses_
DerivedClasses derivedClasses; // constructed with derivedClasses_
// ... same as before
};
Now I can do:
Class c;
Class::DerivedClasses::const_iterator = c.derivedClasses.begin();
boost::algorithm::find( c.derivedClasses, & c );
...
In this example, the nested class is not so coupled to Class, so it could be defined outside, but you could find examples with a stronger bound.
Well, after this long post, I notice that I did not really answer your question :). So no, I never actually used memberspaces in my code, but I think it has its applications.
I have considered it once or twice, notably when I was writing a facade class for a library: the facade was meant to make the library easier to use by having a single entry point, but as a consequence it had several member functions, which were all related, but with different degrees of "relatedness". Moreover, it represented a collection of objects, so it contained iteration-related typedefs and member functions in addition to "features-oriented" member functions. I considered using memberspaces to divide the class in logical "subspaces" in order to have a cleaner interface. Don't know why I haven't done it.
No, I've never used that.
A good use for it? Maybe you can use it to show your colleagues that you are better they are... just like some pleople use templates where they shoudn't, for a complex solution to a simple problem (note that templates, unlike memberspace idiom, sometimes are useful).
Any syntax flexibility is always welcomed regardless of whether is it is potentially confusing or not. In fact the trick is used in boost.array, this is a minimal implementation:
#include<cassert>
template<unsigned N>
struct fixed_array{ /* bla bla */
static unsigned size(){
return N;
}
};
int main(){
fixed_array<3> arr;
assert(arr.size() == 3); //like a stl container
assert(fixed_array<3>::size() == 3); //more proper, but less generic wrt stl containers
return 0;
}
so if the user wants to see a static member function/static member variable/nested class as a property of the instance and not the class then he/she can. Useful to write generic code for example, and it is not confusing at all in this example.

Why are C++ classes allowed to have zero data members?

question about c++
why minimal number of data members in class definition is zero
i think it should be one , i.e pointer to virtual table defined by compiler
thanks a lot
It is often useful to have a class with no data members for use in inheritance hierarchies.
A base class may only have several typedefs that are used in multiple classes. For example, the std::iterator class template just has the standard types defined so that you don't need to define them in each iterator class.
An interface class typically has no data members, only virtual member functions.
A virtual table has nothing to do with the data members of a class.
I’m working on a library that sometimes even uses types that – gasp! – aren’t even defined, much less have data members!
That is, the type is incomplete, such as
struct foobar;
This is used to create an unambiguous name, nothing more.
So what is this useful for? Well, we use it to create distinct tags, using an additional (empty, but fully defined) type:
template <typename TSpec>
struct Tag {};
Now you can create distinct tags like so (yes, we can declare the type inside the template argument list, we do not need to declare it separately):
using ForwardTag = Tag<struct Forward_>;
using RandomAccessibleTag = Tag<struct RandomAccessible_>;
These in turn can be used to disambiguate specialized overloads. Many STL implementations do something similar:
template <typename Iter>
void sort(Iter begin, Iter end, RandomAccessibleTag const&) …
Strictly speaking, the indirect route via a common Tag class template is redundant, but it was a useful trick for the sake of documentation.
All this just to show that a (strict, static) type system can be used in many different ways than just to bundle and encapsulate data.
Well, actually C++ mandates that all classes must occupy some space (You need to be able to generate a pointer to that class). They only need a pointer to a vtable though, if the class is polymorphic. There's no reason for a vtable at all in a monomorphic class.
Another use of a class with no data-members is for processing data from other sources. Everything gets passed into the class at runtime through pointers or references and the class operates on the data but stores none of it.
I hadn't really thought about this until I saw it done in a UML class I took. It has it's uses, but it does usually create coupled classes.
Because classes are not structures. Their purpose, contrary to popular belief, is not to hold data.
For instance, consider a validator base class that defines a virtual method which passes a string to validate, and returns a bool.
An instance of a validator may refuse strings which have capital letters in them. This is a perfect example on when you should use a class, and by the definition of what it does, there's clearly no reason to have any member variables.
question about c++ why minimal number of data members in class definition is zero
It is zero because you have various cases of classes that should have no members:
You can implement traits classes containing only static functions for example. These classes are the equivalent of a namespace that is also recognizable as a type. That means you can instantiate a template on the class and make sure the implementation of that template uses the functions within the class. The size of such a traits class should be zero.
Example:
class SingleThreadedArithmetic
{
static int Increment(int i) { return ++i; }
// other arithmetic operations implemented with no thread safety
}; // no state and no virtual members -> sizeof(SingleThreadedArithmetic) == 0
class MultiThreadedArithmetic
{
static int Increment(int i) { return InterlockedIncrement(i); }
// other arithmetic operations implemented with thread safety in mind
}; // no state and no virtual members -> sizeof(MultiThreadedArithmetic) == 0
template<class ThreadingModel> class SomeClass
{
public:
void SomeFunction()
{
// some operations
ThreadingModel::Increment(i);
// some other operations
}
};
typedef SomeClass<SingleThreadedArithmetic> SomeClassST;
typedef SomeClass<MultithreadedArithmetic> SomeClassMT;
You can define distinct class categories by implementing "tag" classes: classes that hold no interface or data, but are just used to differentiate between separate "logical" types of derived classes. The differentiation can be used in normal OOP code or in templated code.
These "tag" classes have 0 size also. See the iterators tags implementation in your current STL library for an example.
I am sure there are other cases where you can use "zero-sized" classes.

C++ design with static methods

I would like to define as class X with a static method:
class X
{
static string get_type () {return "X";}
//other virtual methods
}
I would like to force classes which inherit from X to redefine the get_type() method
and return strings different from "X" (I am happy if they just redefine get_type for now).
How do I do this? I know that I cannot have virtual static methods.
Edit: The question is not about the type_id, but in general about a static method that
should be overriden. For example
class X {
static int getid() {return 1;}
}
template<int id>
class X {
public:
static int getid() { return id; }
};
class Y : public X<2> {
};
You haven't overridden the method, but you've forced every subclass to provide an ID. Caveat: I haven't tried this, there might be some subtle reason why it wouldn't work.
If I'm not mistaken, to call the static method, you have to invoke the method by specifying the exact name of the class, e.g X::get_type();, DerivedClass::get_type() etc and in any case, if called on an object, the dynamic type of the object is not taken into account. So at least in the particular case, it will probably only be useful in a templated context when you are not expecting polymorphic behavior.
However, I don't see why it shouldn't be possible to force each interesting class (inherited or not, since "compile-time polymorphism" doesn't care) to provide this functionality with templates. In the following case, you must specialize the get_type function or you'll have a compile-time error:
#include <string>
struct X {};
struct Derived: X {};
template <class T> std::string get_type() {
static_assert(sizeof(T) == 0, "get_type not specialized for given type");
return std::string();
}
template <> std::string get_type<X>() {
return "X";
}
int main() {
get_type<X>();
get_type<Derived>(); //error
}
(static_assert is C++0x, otherwise use your favourite implementation, e.g BOOST_STATIC_ASSERT. And if you feel bad about specializing functions, specialize a struct instead. And if you want to force an error if someone accidentally tries to specialize it for types not derived from X, then that should also be possible with type_traits.)
I'd say you know the why but just in case here's a good explanation:
http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=/com.ibm.xlcpp8l.doc/language/ref/cplr139.htm
It looks like your going to have to design your way out of this. Perhaps a virtual function that wraps a Singleton?
Don't do that, use typeid instead.
To make a long story short, you can't do it. The only way to require a derived class to override a base class function is to make it a pure virtual (which can't be static).
You can't do this for a number of reasons. You can't define the function in X and have it be pure virtual. You can't have virtual static functions at all.
Why must they be static?
Here you go
class X
{
static string get_type() {return "X"; }
};
class Y : public X
{
static string get_type() {return "Y"; }
};
The code above does exactly what you requested: the derived class redefines get_type and returns a different string. If this is not what you want, you have to explain why. You have to explain what is it you are trying to do and what behavior you expect from that static method. If is absolutely unclear form your original question.
You mention a few places about guaranteeing that the child types yield unique values for your function. This is, as others have said, impossible at compile time [at least, without the use of templates, which might or might not be acceptable]. But if you delay it until runtime, you can maybe pull something similar off.
class Base {
static std::vector<std::pair<const std::type_info*, int> > datas;
typedef std::vector<std::pair<const std::type_info*, int> >::iterator iterator;
public:
virtual ~Base() { }
int Data() const {
const std::type_info& info = typeid(*this);
for(iterator i = datas.begin(); i != datas.end(); ++i)
if(*(i->first) == info) return i->second;
throw "Unregistered Type";
}
static bool RegisterClass(const Base& p, int data) {
const std::type_info& info = typeid(p);
for(iterator i = datas.begin(); i != datas.end(); ++i) {
if(i->second == data) {
if(*(i->first) != info) throw "Duplicate Data";
return true;
}
if(*(i->first) == info) throw "Reregistering";
}
datas.push_back(std::make_pair(&info, data));
return true;
}
};
std::vector<std::pair<const std::type_info*, int> > Base::datas;
class Derived : public Base { };
const DerivedRegisterFlag = Base::RegisterClass(Derived(), 10);
class OtherDerived : public Base { };
const OtherDerivedRegisterFlag = Base::RegisterClass(OtherDerived(), 10); //exception
Caveats: This is completely untested. The exceptions would get thrown before entering main if you do it this way. You could move the registration into constructors, and accept the per-instance overhead of registration checking if you'd rather.
I chose an unordered vector for simplicity; I'm not sure if type_info::before provides the necessary semantics to be used as a predicate for a map, and presumably you won't have so many derived classes that a linear search would be problematic anyhow. I store a pointer because you can't copy type_info objects directly. This is mostly safe, since the lifetime of the object returned by typeid is the entire program. There might be issues when the program is shutting down, I'm not sure.
I made no attempt to protect against static order of initialization errors. As written, this will fail at some point.
Finally, no it isn't static, but "static" and "virtual" don't really make sense together anyhow. If you don't have an instance of the type to act on, then how do you know which overwritten method to chose? There are a few cases with templates where you might legitimately want to call a static method without an actual object, but that's not likely to be common.
*edit: Also, I'm not sure how this interacts with dynamically linked libraries and the like. My suspicion is that RTTI is unreliable in those situations, so obviously this is similarly unreliable.
Use Delphi, it supports virtual static members on classes. ;>
Apologies for resurrecting this thread, but I've just encountered this moral crisis as well. This is a very bold and possibly foolish statement to make, but I wholeheartedly disagree with what most people are saying about static virtual not making any sense. This dilemma stems from how static members are commonly used versus what they're actually doing underneath.
People often express facts using static classes and/or members - something that is true for all instances if instances are relevant, or simply facts about the world in the case of static classes. Suppose you're modelling a Philosophy class. You might define abstract class Theory to represent a theory which is to be taught, then inherit from Theory in TheoryOfSelf, TheoryOfMind and so on. To teach a Theory, you'd really want a method called express() which expresses a theory using a particular turn of phrase appropriate to the audience. One would assume that any inheriting class should expose an identical method express(). If I were able to, I would model this relationship using static virtual Theory.express() - it is both a statement of fact transcending the concept of instances (therefore static) and nonspecific, requiring a specific implementation by each type of theory (therefore virtual).
I completely agree however with people justifying the prohibition on the grounds of what static is actually doing - it makes perfect sense in terms of coding principles, the issue arises from the customary ways people commonly model the real world.
The best resolution to this problem I've been able to think of is to model Theory as a singleton instead - there may be an instance of a theory, but there's only ever one of them. If you want an alternative, it's a different type, so create a new derived class. To me this approach just seems arbitrary and introduces unnecessary noise.