Inheritance is called object code level reuse? - c++

In object oriented programming class the instructor is telling that
Inheritance is called Object code level reuse.
But I was thinking how because We don't have the source code is not available in object or any other compiled library file so how can we inherit a function or class for reuse if We don't have the source code.
Normally we inherit a class whose source code or class information is available.
Can somebody explain it?
The other question need the explanation is :
how container-ship is different than inheritance?
Because I read that container-ship is a derive which has a relation-ship from base class as "has a relation", which I feel is inheritance only.
Any explanation is appreciated.
Thanks.

Related

C++ class extension technology

I know the official answer for "extension class in C++ like objective-C or c#" is NO. But is there any hack ways to implement this? And what is the cost?
I ask this because my colleague use my parser to generate C++ class files from a special format txt file. They complained that it is difficult to extension the class.
I can't force them to use inheritance, because the class generated is like this:
class A {}
class B : A {}
if my colleague extends A like this:
class C : A {}
then the B class will not benefit from the C class. That means: In our situation, if class C : A, B is meant to inherit from A, then now B should inherit from C now. But it is not possible since the B has hard code to inherit from A. That means, inheritance is not a good option, the truly demand is to extend A.
And using A as a member in a new class is not an option, either. Since our logic is more like a "is-A", not a "has-A", force make A as a member will make the code hard to read.
Currently they directly modify the class header file, and any new member functions is implement in a new cpp file(thanks to C++ class file structure), so if the class changes, the origin cpp file will regenered, they won't care about it, while they use git to merge the new generated header file to the file they have modified.
I can write a parser to scan the header file and do the merge, but write a parser to fully implement C++ standard BNF(http://www.externsoft.ch/download/cpp-iso.html) is difficult.
Currently I decide to use macros, like the mechanism used by flex and bison to replace the action in .y file to the generated c file. But I wondered if there's a easy way.
A common C++ solution is freeFunction(A&) instead of creating class B. Unlike pure OO languages, C++ has free functions which are not class members. Your freeFunction_B(A&) and your colleague's freeFunction_C(A&)` will not interfere.
Obviously this is not a solution when you need to add data members. In that case, there's another option. Leave open the base class:
template<typename BASE> class B : public BASE {
// ...
}
This allows both B<A> and B<C<A>>. Slight downside: C<B<A>> is not the same type as B<C<A>>, which is logical. The members have to be in a certain order in memory, and there are two choices.
(General advice: code generation and C++? That means templates)
As doing a research for some times, I think the term "monkey patch" is the technology what I'm looking for, but it seems only can be implemented with languages which has the reflection feature.
Currently I use "has-a" extension in my code instead of "is-a" to avoid changing the generated code.

How to use c++ classes without names?

I encountered a problem in opensource c++ code. The following is a small and simplified version to describe my problem:
#include <iostream>
using namespace std;
#define TOGETHER2(a,b) a ## b
#define TOGETHER(a,b) TOGETHER2(a,b)
#define GENERATE_NAME(a) TOGETHER(a,__COUNTER__)
#define GENERATE GENERATE_NAME(__seed_)
class base{
}b;
class GENERATE:public base{
}GENERATE;
class GENERATE:public base{
}GENERATE;
class GENERATE:public base{
}GENERATE;
class GENERATE:public base{
}GENERATE;
int main(){
return 0;
}
As we can see, the author defines several classes, which inherites a base class. But the author do not care about the names of the classes. So I wonder how can I use those classes without specifying their names?
Is this a kind of design pattern in c++ that I don't know?
Thank you :)
I want to add my guesses to make the question clear.
My guesses:
The names of these classes are generated from __seed_, but when I search through the files, I can not find other references to __seed_, So I am sure The author did not use the names __seed_1, __seed_2 to create classes. (Actually the author said the the comments that she did not care about the names of the classes)
I also guessed that the author may have used those classes through the interface defined in the base class(virtual function). To do that, the author still needed to create these classes, but as I mentioned I could not find __seed_ in other parts of the code, So the author couldn't create classes, and therefore virtual function do not work either.
Actually, I tried remove these class definitions, and strangely the code compiles correctly. However, It lost some of functionalities, but It did not just core dump. It could still finish some tasks successfully u
So, do anyone know:
How can we use those classes without specifying their names?
Is this design a certain kind of design pattern?
In which situation should we define class without caring about their names?
As I mentioned, I removed some part of the code, and It compiled. How could this happen? I mean, Since I remove many classes from the source code, then If other parts of the code references those classes, the source can not compile. And If it compiles, Can I just conclude that those classes are not needed?
ADDED:
As some of you recommended,
the full source code is here: MIT Cryptdb. In the file ./main/rewrite_const.cc, the author used macro ANON(lion 25) to define many classes without caring about their names.
Really appreciate your help :)
I recommend you to edit the code and add names for the classes. This is a strange design pattern, and I wouldn't recommend you to use such pattern for anything, unless you want to prevent others from using your classes.
If the author wants you to use those classes, there is probably some way you can use them without editing the code and adding the names. You should consult the documentation for this.
As I mentioned, I removed some part of the code, and It compiled. How could this happen? I mean, Since I remove many classes from the source code, then If other parts of the code references those classes, the source can not compile. And If it compiles, Can I just conclude that those classes are not needed?
All those generated classes are derived from the base class. So if you remove one class, all classes that come after it receive a new generated name. If the code now compiles, it means the other code is only calling the methods that are part of the base class. But the other code is now using other classes than what it originally used, which causes the errors you observe.
Consider this:
Initially the generated classes have names A, B, and C.
You remove class A.
Now the generated classes have names A and B. Class named C no longer exists, so the code that uses it should no longer compile. And the code that used class A and B before, it is now using the classes that used to be B and C.
These classes do have names. Only that these names are not revealed to the human reader and are not specified before the preprocessor has run. (If you run the compiler with option -E, it will only run the preprocessor stage and output the code as the compiler proper sees it, including the class names.)
AFAIK, there is no sensible reason to hide the names in this way. If the author doesn't want humans to write code that uses these classes, then there are other ways.
Defining such names in a header file to be included by the user implies that they cannot be used from within the library other than via polymorphism (because the library cannot know their names). This is the reason why removing them made no difference regarding compilation.

Factory Pattern in C++ -- doing this correctly?

I am relatively new to "design patterns" as they are referred to in a formal sense. I've not been a professional for very long, so I'm pretty new to this.
We've got a pure virtual interface base class. This interface class is obviously to provide the definition of what functionality its derived children are supposed to do. The current use and situation in the software dictates what type of derived child we want to use, so I recommended creating a wrapper that will communicate which type of derived child we want and return a Base pointer that points to a new derived object. This wrapper, to my understanding, is a factory.
Well, a colleague of mine created a static function in the Base class to act as the factory. This causes me trouble for two reasons. First, it seems to break the interface nature of the Base class. It feels wrong to me that the interface would itself need to have knowledge of the children derived from it.
Secondly, it causes more problems when I try to re-use the Base class across two different Qt projects. One project is where I am implementing the first (and probably only real implementation for this one class... though i want to use the same method for two other features that will have several different derived classes) derived class and the second is the actual application where my code will eventually be used. My colleague has created a derived class to act as a tester for the real application while I code my part. This means that I've got to add his headers and cpp files to my project, and that just seems wrong since I'm not even using his code for the project while I implement my part (but he will use mine when it is finished).
Am I correct in thinking that the factory really needs to be a wrapper around the Base class rather than the Base acting as the factory?
You do NOT want to use your interface class as the factory class. For one, if it is a true interface class, there is no implementation. Second, if the interface class does have some implementation defined (in addition to the pure virtual functions), making a static factory method now forces the base class to be recompiled every time you add a child class implementation.
The best way to implement the factory pattern is to have your interface class separate from your factory.
A very simple (and incomplete) example is below:
class MyInterface
{
public:
virtual void MyFunc() = 0;
};
class MyImplementation : public MyInterface
{
public:
virtual void MyFunc() {}
};
class MyFactory
{
public:
static MyInterface* CreateImplementation(...);
};
I'd have to agree with you. Probably one of the most important principles of object oriented programming is to have a single responsibility for the scope of a piece of code (whether it's a method, class or namespace). In your case, your base class serves the purpose of defining an interface. Adding a factory method to that class, violates that principle, opening the door to a world of shi... trouble.
Yes, a static factory method in the interface (base class) requires it to have knowledge of all possible instantiations. That way, you don't get any of the flexibility the Factory Method pattern is intended to bring.
The Factory should be an independent piece of code, used by client code to create instances. You have to decide somewhere in your program what concrete instance to create. Factory Method allows you to avoid having the same decision spread out through your client code. If later you want to change the implementation (or e.g. for testing), you have just one place to edit: this may be e.g. a simple global change, through conditional compilation (usually for tests), or even via a dependency injection configuration file.
Be careful about how client code communicates what kind of implementation it wants: that's not an uncommon way of reintroducing the dependencies factories are meant to hide.
It's not uncommon to see factory member functions in a class, but it makes my eyes bleed. Often their use have been mixed up with the functionality of the named constructor idiom. Moving the creation function(s) to a separate factory class will buy you more flexibility also to swap factories during testing.
When the interface is just for hiding the implementation details and there will be only one implementation of the Base interface ever, it could be ok to couple them. In that case, the factory function is just a new name for the constructor of the actual implementation.
However, that case is rare. Except when explicit designed having only one implementation ever, you are better off to assume that multiple implementations will exist at some point in time, if only for testing (as you discovered).
So usually it is better to split the Factory part into a separate class.

Why can't we create an instance of an abstract class?

I found in many places that :
An Abstract Class is a class which is supposed to be used as a base class.
An Abstract Class is a class which has atleast one Pure Virtual Function.
But one thing that always strikes my mind is why can't we create an instance of an abstract class? Many places on the Internet say there is no point in creating an instance, or some say that they are supposed to be used as base classes. But why is it an error to create an instance of an abstract class?
Your void bar()=0; is not valid -- the =0 notation can only be used with virtual functions.
The whole point of an abstract class is that it's abstract -- you've defined an interface but not an implementation. Without an implementation, instantiating the class wouldn't produce a meaningful or useful result. If it does/would make sense to instantiate objects of that class, then you simply don't want to use an abstract class in the first place.
For example, consider device drivers. We might have a driver for an abstract storage device. We define some capabilities for that device, such as reading and writing data. That abstract class gives any code that wants to read/write data the ability to work with an concrete class that derives from that abstract class.
We can't just instantiate our abstract storage device though. Instead, we need a concrete object like a thumb drive, disk drive, etc., to actually read from/write to. The concrete class is needed because we need code specific to the actual device to carry out the commands we've defined in our abstract base. Our abstract storage class just has a read or write, but do the reading or writing, we need a driver for a specific device. One might know how to talk to a SATA hard drive, while another knows how to talk to a USB thumb drive and a third knows how to read from or write to an SD card. We can't, however, just say "I'm going to create an abstract storage device", and talk to it without defining the actual code that will translate a "write" command into (for example) the right signals going over SATA, USB, Firewire, etc., to get the data onto a real drive.
As such, attempting to instantiate our abstract class makes no sense, and isn't allowed. We just use the abstract base class so the rest of the system can deal with all devices uniformly. The rest of the code doesn't care how the signals are different from each other -- it just sees a bunch of disk drives, and can work with all of them, even though the details of reading data over USB are completely different from reading over Firewire (for example).
An abstract class represents something that isn't specific enough to be instantiated. For instance, what if someone asked you to create a vehicle? You'd have to ask, "what kind of vehicle?" You wouldn't know whether to create a car, a sled, or a space shuttle. There's no such object as a "vehicle". Yet "vehicle" is a useful abstraction that can be used to group objects, indicating common behaviors among them. That's what abstract classes are for.
An abstract class is more than an interface. It may have data members. It may have member functions that are not pure virtual, or non-virtual at all. Even a pure virtual function may have a body, providing a default implementation. So this is not about a physical impossibility of instantiating an abstract class.
The main point is that a pure virtual function is a virtual function that must be overridden by a derived class. That means that a derived class must be defined, and the way to force that is to forbid the instantiation of an abstract class.
An abstract class is not specific enough to be instantiated. Not necessarily because it is missing a definition of a function, because it may not be missing it. It is not specific enough because it represents an abstract concept, which must be made more specific before it can be instantiated.
That's the whole point of an abstract class: that some details must be provided by the implementor.
Think about it: what would be the point of marking a class as abstract if you could instantiate it directly? Then it would be no different than any other class.
The reason an abstract class cannot be instantiated is: what do you do if you execute the pure virtual function? That would be a serious error, and it's better to catch that at compile-time than at runtime.
In abstract class no method definition is given, only structure is provided. If we could instantiate abstract class and call those method, it will be a huge mess. Abstract class is use to maintain a design pattern of the code.
Only Chuck Norris can instantiate an abstract class.
https://api.chucknorris.io/jokes/ye0_hnd3rgq68e_pfvsqqg

Hierarchy inheritance

I had faced the problem. In my C++ hierarchy tree I have two branches for entities of difference nature, but same behavior - same interface. I created such hierarchy trees (first in image below).
And now I want to work with Item or Base classes independetly of their nature (first or second). Then I create one abstract branch for this use. My mind build (second in image below).
But it not working. Working scheme seems (third in image below).
It's bad logic, I think...
Do anybody have some ideas about such hierarchy inheritance? How make it more logical? More simple for understanding?
Image
Sorry for my english - russian internet didn't help:)
Update:
You ask me to be more explicit, and I will be.
In my project (plugins for Adobe Framemaker) I need to work with dialogs and GUI controls. In some places I working with WinAPI controls, and some other places with FDK (internal Framemaker) controls, but I want to work throw same interface.
I can't use one base class and inherite others from it, because all needed controls - is a hierarchy tree (not one class).
So I have one hierarchy tree for WinAPI controls, one for FDK and one abstract tree to use anyone control.
For example, there is an Edit control (WinEdit and FdkEdit realization), a Button control (WinButton and FdkButton realization) and base entity - Control (WinControl and FdkControl realization).
For now I can link my classes in realization trees (Win and Fdk) with inheritence between each of them (WinControl is base class for WinButton and WinEdit; FdkControl is base class for FdkButton and FdkEdit). And I can link to abstract classes (Control is base class for WinControl and FdkControl; Edit is base class for WinEdit and FdkEdit; Button is base class for WinButton and FdkButton). But I can't link my abstract tree - compiler swears.
In fact I have two hierarchy trees, that I want to inherite from another one.
Update:
I have done this quest! :)
I used the virtual inheritence and get such scheme (http://img12.imageshack.us/img12/7782/99614779.png). Abstract tree has only absolute abstract methods. All inheritence in abstract tree are virtual. Link from realization tree to abstract are virtual. On image shown only one realization tree for simplicity.
Thanks for help!
C++ supports multiple inheritance, so you can have the union of (2) and (3), making sure that AbstractBase is always declared as a virtual base class.
Without knowing the real meaning and purpose of the various classes, it's difficult to offer any better advice.
It's not clear from the description if this would work for you but typically classes with a common interface would define the interface in AbstractBase and then have concrete instances inherit directly from that (FirstItem, SecondItem).
Why the extra indirection(s) in your examples? What's expected to be in AbstractItem, FirstBase and SecondBase?
For using different implementations of one interface, on could use:
the Bridge Design Pattern
You might couple this with a Factory Design Pattern so as to construct your two implementations differently.
However, it may look too simple for your classes architecture.
But as the comments under your answer say: it is difficult to imagine the job/role of your classes with such names. You should be more explicit, so as we can think of a precise design.