Things that cannot be inherited - c++

I've been asked to name three things that can not be inherited from the base class.
Apart from private member functions, what else can I add?
I thought about friend functions but since they don't actually belong to the class, they have nothing to do with inheritance.

A few obvious ones you usually care about are constructors, assignment operators and destructors.
In all these cases, a new version specific to the derived class is either provided by the user, or else synthesized by the compiler (though C++11 also adds some capabilities for things like simply deleting one that you don't want available).
I should probably add that "can not be inherited" isn't necessarily exactly correct. For example, C++11 adds inheriting constructors (but they weren't in C++98/03, which is what most courses still deal with). Even in C++11, you don't inherit them by default.

Private member variables, and private bases. You also cannot inherit template arguments, COM __uuids, and whether or not the class is exported from a DLL.
Assignment operators cannot be inherited.

Related

Can copy-constructor with delete qualifier be private? [duplicate]

In order to make an object non-copiable we can explicitly delete both its copy-constructor and copy-assignment operator.
My question is: What is the right place to do it - in the public, private or protected section of the class? And - does this choice make any difference?
what is the right place to do it - in the public, private or protected section of the class?
I would put them in the public section.
This is because deleting a constructor or an assignment operator is orthogonal to making them private / protected; and when these aren't deleted, they are public by default. Putting the deletions in one of those two sections seems to me like hinting "If I hadn't deleted them, I would have made them private/protected" - which is not a message you want to convey in your case.
Note, though, that the compiler doesn't care which section you put the deletion in.
Does where we put the deleted definition make any difference?
From a pure language standpoint it makes absolutely zero difference. Name lookup and overload resolution happen before access checking. And attempting to refer to a deleted function at the end of overload resolution makes your program ill-formed, period. A compiler may or may not issue another diagnostic about the accessibility, but the program already has an error that must be reported.
So you can put that deleted definition with whatever accessibility you desire. I think most will keep it private, to be inline with the "old" practice of making a class non-copyable (put the declaration of those members in the private section of the class, and not define them), if only to help those who know the old ways "get it" sooner. A mixture of idioms, if you would.
Marking as private is also something you can't avoid if you need to support both C++03 and C++11 mode. With the help of a macro, a header can be made to conform to both standards easily:
#if __cplusplus >= 201103L
#define DELETED_DEFINITION = delete
#else
#define DELETED_DEFINITION
#endif
class noncopyable {
private:
// This header can be compiled as both C++11 and C++03
noncopyable(noncopyable const&) DELETED_DEFINITION;
void operator=(noncopyable const&) DELETED_DEFINITION;
};
From Scott Meyers's book, Effective Modern C++ (Item 10), it seems that it is better to define them as public:
By convention, deleted functions are declared public, not private.
There’s a reason for that. When client code tries to use a member
function, C++ checks accessibility before deleted status. When client
code tries to use a deleted private function, some compilers complain
only about the function being private, even though the function’s
accessibility doesn’t really affect whether it can be used. It’s worth
bearing this in mind when revising legacy code to replace
private-and-not-defined member functions with deleted ones, because
making the new functions public will generally result in better error
messages.
In addition, I believe that a deleted copy constructor/assignment, should be part of the class interface to be shared with ALL of the class users. Such kind of information should not be kept as secret by making them private.
delete works just as well with private access.
The effect of delete is to cause an error if the function is chosen by overload resolution.
The effect of private is to cause an error if the function is chosen by overload resolution from outside the class or its friends.
If both errors apply, the ultimate outcome is the same either way, but public might help avoid compiler messages about access privileges, which could cause confusion.
The access of a deleted function is irrelevant. In fact, for class members, it would have made more sense to add an additional access specifier (delete:). I suspect the reason they didn't do that, was that it wouldn't work for non-member functions.
For things like the copy constructor, it makes more sense stylistically to put it in the public section. The fact that a class doesn't have a copy constructor is a pretty major fact to know about the interface to the class.
For internal functions where you are declaring a particular overload as deleted in order to get compiler-time detection of an error, it makes sense to declare the function in the same section as all the other overloads.

C++ static-only class

I have a bunch of functions that I want to put in either a separate namespace or a class. Out of the two, which would be better? If it's the latter, how should I go about it? I mean, I don't have any instance members, so should I specify the constructor as private? Or delete it?
Either way, it will look something like this to give you an idea:
myproject::foo::f()
C++ namespaces and class can both contain functions and other types, but there are some key differences in behavior. You'll have to decide which is best for your particular circumstance.
Classes can be templated, namespaces can't. This provides a way to pass a set of template arguments to a whole group of functions and other types. Combined with typedef, this can be very powerful.
You can use using namespace xyz; to bring a whole group of namespace members into any scope. Classes can be inherited to bring them into scope (has not much effect if there are no instance members, due to the empty base optimization, but static members can then be used without qualification), but this only works inside other classes. Free functions would have to explicitly qualify all access to members of the class.
Namespaces participate in argument-dependent lookup, members of a parent class don't.
If you want to use the trick of inheriting a class to supply template arguments and gain unqualified access to its static members, then you should leave the constructor and destructor as defaulted and trivial, instead of deleting or making them inaccessible. In C++11, you can mark the constructor both protected and defaulted.
If you use the class it is best to declare the default constructor, copy constructor, assignment operator, and destructor private / unimplemented (plus maybe some more for C++11). If you don't you'll have a class that can be used to make useless objects. If you use a namespace you don't have to do any of that.
Classes are made for objects. Using them as containers of static functions, no member data, is more abuse than use.

Advantages of typedef over derived class?

Simply put, what are the (or are there any) differences between doing say
class MyClassList : list<MyClass> { };
vs
typedef list<MyClass> MyClassList;
The only advantage that I can think of (and its what lead me to this question) is that with the derived class i can now easily forward declare MyClassList as
class MyClassList;
without compiler error, instead of
class MyClass;
typedef list<MyClass> MyClassList;
I can't think of any differences, but this made me wonder, are there cases in which a typedef can be used that a simple derived class can't?
Or to put it another way, is there any reason why I shouldn't change all my typedef list<...> SomeClassList; to the simple derived class so that I can easily forward declare them?
In C++ it is NOT recommended to derive from an STL container, so don't do it.
A typedef is just creating an alias for an existing type, as it were, so typedef std::list<MyClass> MyClassList; creates a "new type" that is called MyClassList which you can now use as follows:
MyClassList lst;
Changing your typedefs to a derived class is a bad idea. Don't do it.
typedef is intended exactly for this purpose -- to alias type names. Its very idiomatic and won't confuse anybody familiar with C++.
But to address why inheriting may be a bad idea.
std::list does not have a virtual destructor. Meaning MyClassList wouldn't have its destructor called when deleted through the base class. So this is typically frowned upon. In your case, you have no intention of putting any members in MyClassList, so this becomes a moot point until the next programmer sees inheritance as an invitation to add new members/override functions etc. They may not realize that std::list's destructor is not virtual and not realize that in some cases MyClassList's destructor won't get called.
Well, a typedef can only do what its name suggests while a derived class can possibly be a full-blown makeover of its base(s). So while there may not be much of a difference if you limit yourself to "just" deriving (and not add any members, or override anything, etc) as far as the compiler is concerned, there might be a big difference as far as human readers of the code are concerned.
One might wonder "why is this a derived class when a typedef would suffice"? Most people would assume that there must be a reason, so you would make life harder to the code's future maintainers. A typedef, on the other hand, is a very specific tool and does not raise questions.
And while we 're on the topic of maintenance don't forget that as most things in C++, this "nothing will go wrong as long as we are disciplined and don't cross this line" is an open invitation to disaster. Since the compiler isn't there to stop you, someone, someday, will cross the line.
A number of things have been mentioned. A big thing however:
Deriving from a type does not inherit all the constructors.
If there are a number of non-default constructors, you won't have them when inheriting (you'd have to forward them to the base constructor).
Typedefs have no such 'issue'.
Now, typedefs do not generate unique typeids. If you want that, and not have the overhead or other disadvantages of inheritance, look at boost: it has a strong typedef macro that generates a unique typeid:
http://www.boost.org/doc/libs/1_37_0/boost/strong_typedef.hpp
A typedef is an alias, while a class is a new type.
In the first case, the compiler has to simply replace MyClassList with list<MyClass>.
In the second case, MyClassList involve the generation of default constructor, copy constructor assignment operator, destructor, and - where c++11 is in use - even move constructor and move assignment.
In default cases, since MyClassList has no additional functionality, optimization will most likely wipe them out.
Note: I found the "deriving classes with non virtual destructor is not recommended" argument a weak one. A C++ developer should know that derivation does not necessarily imply polymorphism. A class that is not deleted through a pointer to its base doesn't need a virtual destructor, like a class whose method is not designed to be "called" through a base pointer does not require that method to be virtual.
Simply, if a destructor is not virtual, don't treat that type as "polymorphic" on deletion.
In this sense, destructor are not different from other virtual or non virtual methods.
If this argument has to be considered strong, then, all classes that don't have "all virtual" method shouldn't be derived!

Class function member not depending on the class members

Is there a good reason why should a class function member be part of the class if it does not depend on any of the members of the class?
No. In fact, you should prefer free-functions over member functions. Only functions that really need to operate on the members should be member functions, the rest should use them to provide functionality.
Assuming you mean "does not depend on any non-public members", Scott Meyers once answered a definite no to that question.
However, he focused only on encapsulation: encapsulation is improved by making those functions non-members.
Other considerations can, for example, include that you cannot call operator<< on a temporary if the operator is defined as a non-member. (Why would you ever want to do that? Well, for example to build up a string argument from constituent parts, iostream-style.)
And the considerations can include simply how natural and clear the usage notation is. The notation with nested calls (as for non-members) can be rather annoying and unclear. That's why we have -> as syntactic sugar for * dereferencing + member selection.
So, if you focus only on encapsulation, then move those member functions out of class, as Scott Meyers adviced. And otherwise, make an engineering decision where aspects such as usability and notational clarity are also considered. Anyway, don't fret about it: it's probably not incredibly important. :-)
Cheers & hth.,
If its correlated with the meaning of the class, you should put it together even if it do not use any member of the Class.
The reason it for simply the development, and for a future developer know where to look.
It often happens when overriding a virtual function. If the base class has a pure virtual along the lines of getWidgetCount(), for example, and your derived class doesn't support widgets, it would just return 0.
the most common case concern utility classes for example if i have to develop functions to convert BSTR to string and vice versa , i can create a class with static methods.
it's useful to package functions concerning the same area in the same class, another solution is to package them in the same namespace, but unfortunatly namespaces are not very used even in the well known c++ librairies.
and for other cases adding method to a class with no relation with other members increase the lack of cohesion and the metric LCOM will be high, and the design will be impacted.

Is it always evil to have a struct with methods?

I've just been browsing and spotted the following...
When should you use a class vs a struct in C++?
The consensus there is that, by convention, you should only use struct for POD, no methods, etc.
I've always felt that some types were naturally structs rather than classes, yet could still have a few helper functions as members. The struct should still be POD by most of the usual rules - in particular it must be safe to copy using memcpy. It must have all member data public. But it still makes sense to me to have helper functions as members. I wouldn't even necessarily object to a private method, though I don't recall ever doing this myself. And although it breaks the normal POD rules, I wouldn't object to a struct having constructors, provided they were just initialise-a-few-fields constructors (overriding assignment or destructors would definitely be against the rules).
To me a struct is intuitively a collection of fields - a data structure node or whatever - whereas a class is an abstraction. The logical place to put the helper functions for your collection-of-fields may well be within the struct.
I even think I once read some advice along these lines, though I don't remember where.
Is this against accepted best practice?
EDIT - POD (Plain Old Data) is misrepresented by this question. In particular, a struct can be non-POD purely because a member is non-POD - e.g. an aggregate with a member of type std::string. That aggregate must not be copied with memcpy. In case of confusion, see here.
For what it's worth, all the standard STL functors are defined as structs, and their sole purpose is to have member functions; STL functors aren't supposed to have state.
EDIT: Personally, I use struct whenever a class has all public members. It matters little, so long as one is consistent.
As far as the language is concerned, it doesn't matter, except for default private vs. public access. The choice is subjective.
I'd personally say use struct for PODs, but remember that "POD" doesn't mean "no member functions". It means no virtual functions, constructors, destructor, or operator=.
Edit: I also use structs for simple public-access aggregates of data, even if their members aren't PODs.
I tend to use struct a lot.
For the "traditional" OOP classes (the ones that represent a specific "thing"), I tend to use class simply because it's a common convention.
But most of my classes aren't really OOP objects. They tend to be functors, and traits classes and all sorts of other more abstract code concepts, things I use to express myself, rather than modelling specific "things". And those I usually make struct. It saves me having to type the initial public:, and so it makes the class definition shorter and easier to get an overview of.
I also lean towards making larger, more complex classes class. Except this rarely affects anything, because I lean even more towards refactoring large, complex classes... And then I'm left with small simple ones, which might be made struct's.
But in either case, I'd never consider it "evil". "Evil" is when you do something that actively obfuscates your code, or when you make something far more complex than necessary.
But every C++ programmer knows that struct and class mean virtually the same thing. You're not going to be confused for long because you see a struct Animal {...}; You know that it's a class designed to model an animal. So no, it's not "evil" no matter which way you do it.
When I have control over the style guides, everything is defined as a struct. Historically, I wanted all my objects to be one or the other, since I was taught it was undefined behavior to forward declared a struct as a class, and vice versa (I'm not sure if this was ever actually true, its just what I was told). And really, struct has the more reasonable default state.
I still do the same because I've never been convinced of the value of using it as a form of documentation. If you need to convey that an object only has public members, or doesn't have any member functions, or whatever arbitrary line you chose to draw between the two, you have actual documentation available for that. Since you never actually use the struct or class keyword when using the type, you would need to go hunting for the definition anyhow if you want the information. And with everybody having their own opinion on what struct actually means, its usefulness as self-documentation is reduced. So I shoot for consistency: everything as one or the other. In this case, struct.
Its not a popular way of doing things, to say the least. Fortunately for everybody involved, I very rarely have control over the coding standards.
I use a struct whenever I need an aggregate of public data members (as opposed to class, which I use for types that come with a certain level of abstractions and have their data private).
Whether or not such a data aggregate has member functions doesn't matter to me. In fact, I rarely ever write a struct without also providing at least one constructor for it.
You said, "To me a struct is intuitively a collection of fields - a data structure node or whatever". What you are describing is Plain Old Data. The C++ standard does have an opinion of what POD means with respect to C++ language features. I suggest that, where possible, you adopt the meaning of POD used in C++0x.
I need to find a reference for this, but I thought that, as far as type definitions are concerned, the keywords "struct" and "class" are to be synonyms in C++0x. The only difference being that class defaults to private members, while a struct defaults to public. This means that you'll never see complier error messages like "Type X first seen using struct, now seen using class." once we're all using C++0x.
I think that it is wrong to have strict rules on when to use class and when to use struct. If consistency is important to you, the go ahead and make a coding standard that has what ever sort of rules you like. Just make sure everyone knows that your coding standard relates to how you want you code to look - it doesn't relate to the underlying language features at all.
Maybe to give an example where I break all your rules, you say "To me a struct is intuitively a collection of fields - a data structure node or whatever - whereas a class is an abstraction." When I want to write a class that implements some abstraction, I define the interface as a struct with pure virtual methods (egad!) - this is exposed in a header, as too is a factory method to construct my concrete class. The concrete class is not exposed i a public header at all. Since the concrete class is a secret, it can be implemented however I like and it makes no difference to external code.
I'd suggest that if you think that the keywords struct and class have any relation to the concept of POD, then you're not understanding C++ yet.