let's say I want to instantiate a different type of object depending on certain circumstances, so i would instantiate them inside the body of an if statement. The problem is if you want to use that object later, you need to declare it before instantiation. How does one declare a generic object. Is there something similar to the object class in Java?
I've done some google searching like "generic object c++" and "object class c++" and there doesn't appear to be something like that.
This problem can be solved with interfaces. Now, C++ doesn't know interfaces, but you can easily do something similar with abstract base classes:
class Base { ... }
class A : public Base { ... } // A is a Base
class B : public Base { ... } // B is a Base
...
Base *X; // that's what you will end up using
if (some_condition)
X = new A(); // valid, since A is a Base
else
X = new B(); // equally valid, since B is a Base
This will require you to put common functionality into the base class so that you can actually perform operations on X.
(If you derived all your classes from something like Base, you'd end up with a super-class like it's available in e.g. C# or Java. However, in my opinion, generic programming, ie. templates in C++, have much reduced the need for a super-class like that. I'd wager that you'll be able to find better code designs in most cases.)
Unlike Java, C++ has no "mother" object which all classes inherit from. In order to accomplish what you're talking about, you'd need to use a base pointer of your own class hierarchy.
Animal* a;
if (...) a = new Cat();
else if (...) a = new Dog();
Also, because there's no garbage collection either, it's better to use smart pointers when you do this sort of thing. Otherwise, be sure you remember to delete a. You also need to make sure that Animal has a virtual destructor.
There's no "ancestor of all classes" in C++. But there are some options for doing similar things.
As stakx suggests, make a base class if possible. This is the best from an object-oriented design perspective. Are there common operations that you want to apply to all the objects? If so, try to write an interface, and make the interface a base class. Alternatively, you can use templates to get compile-time polymorphism instead of runtime polymorphism.
If this is too difficult, then look at a wrapper class like boost::any. That can hold any (copyable) type. It's an opaque wrapper, and you have to know the exact type of data that was put into it, to get it back out. For example, if you put in a Derived *, you need to use boost::any_cast<Derived *>(wrapped) to get the data back - boost::any_cast<Base *>(wrapped) won't work.
std::shared_ptr<Base> X( some_condition ? new A() : new B() );
Heap solutions are expensive and error prone. For not too heavy objects without heap allocations on construction the following approach is preferrable:
Derived1 d1;
Derived2 d2;
Base * b = 0;
if (useD1) {
b = &d1;
} else {
b = &d2;
}
Here we peallocate both types we might need on the stack. No heap allocation, no delete operators, no smartpointers. The only problem - doesn't scale to complex classes to be preallocated.
There is no common base class in C++, so you should define such common ancestor yourself if you the author of these classes or you can use void* although I wouldn't recommend the latter.
If you can't modify the classes then you can introduce wrappers that implement the interface that you need as illustrated below:
class A {};
class B {};
class MyBase
{
// Define the interface that you need.
};
class MyA : public MyBase
{
private:
A a;
public:
// Implement MyBase in terms of A.
};
class MyB : public MyBase
{
private:
B b;
public:
// Implement MyBase in terms of B.
};
int main ()
{
MyBase* base = 0;
if (useA)
base = new MyA();
else
base = new MyB();
}
Related
This is very likely a silly question, but I can't seem to figure out if this is at all possible and if it should actually be done.
Say some code relies a lot on using a certain virtual base class acting as an interface and then deriving several subclasses that implements the virtual methods the base class. Is it possible to use functionality not exsisting in the base class (interface) below without completely disregarding the solid principles, when the rest of the program must not see anything but the base class "interface"? Like in the example below, is it possible to use bar() from the B class inside the function that only knows of A? And should I just add bar() to the "interface" instead?
// Base class - "interface"
Class A
{
public:
virtual int foo();
}
// Derived class - implementing the "interface" + more
Class B: public A
{
public:
int foo();
int bar();
}
int main()
{
function(A); // Some magic function that would utlize the bar() method
return 0;
}
The short answer is yes, use the dynamic_cast operator (but see below). The magic function would look something like this:
void function(A& a)
{
B* b = dynamic_cast<B*>(&a);
if (b)
{
// Object is a B...
b->bar();
}
else
{
// fallback logic using only methods on A
}
}
But be aware that many programmers consider this a code smell. In particular, if there's no way to implement the "fallback" branch, then it suggests the function should really accept a B and something in the design may be amiss. (It's hard to say when talking in such generalities, however.) Also be aware that dynamic_cast can be expensive, particularly with complex class hierarchies.
If at all reasonable, it's preferable to move the B-specific logic into the B class somehow. You might also consider making the bar method a member of the A class (A would provide some sensible default implementation). Another approach might be to create a new interface to hold the bar method and have your function accept an object of that type. (The B class would implement both A and the new interface.)
Say we have 2 classes A and B. Both are subclasses of C, the superclass. Now let's assume that C defines a method areYouA(), that is a method that asks the object if it's an object of the A class.
So a possible code, in c++, would be:
C object1 = A()
C object2 = B()
if (object1.areYouA()==true){//crazy code here regarding if it's an A object}
if (object2.areYouA()==false){//crazy code here regarding if it's a B object}
From an OO POV is it correct to add a method to the B and C classes to ask their respective objects if they're of the A class??? If it's not correct, then what could be another approach to this???? My objective is obvious i have 2 classes A and B that i need, at some point i have portions of binary data that could be of the A class or the B class, also an object would initially be of the A class, as it gets full, it's structure needs to change and also some of it's behaviour, therefore becoming an object of the B class. So my approach to this was thinking of an abstract class as parent, and initially declaring a C object but storing an A object, and later storing a B object as it changes.
Is there another approch to this, like a pattern???
ADDITIONAL INFO:
I think i wasnt very clear about this. Let's say i want to store information from an A object in file1, and info from a B object in file2. If use its mother class as an interface, then how can i tell if it's an A object or a B object to store in the respective files?? Should i add an atribute to each object for their filename they belong too??? That means if i need to change the name of the file, then every object needs to change too.
The correct way is to use virtual functions to implement polymorphic behaviour:
struct C
{
virtual void do_crazy_stuff() { } // (see text below)
virtual ~C() { } // always have a virtual d'tor for polymorphic bases
};
struct A : C
{
virtual void do_crazy_stuff() { /* your crazy code for A */ }
};
struct B : C
{
virtual void do_crazy_stuff() { /* your crazy code for B */ }
};
Now you can use the same interface everywhere:
void process_data(C & x) // <-- Note: take argument by reference!!
{
x.do_crazy_stuff();
}
This works on any object of a type derived from C:
int main()
{
A x;
B y;
process_data(x); // calls x.A::do_crazy_stuff
process_data(y); // calls x.B::do_crazy_stuff
}
If you like, you can even declare the base function C::do_crazy_stuff as pure virtual; this makes the base class abstract (so it cannot be instantiated).
First off,
C object1 = A();
C object2 = B();
slices the objects. They are no longer of type A or B, they are C.
You can use pointer for this:
C* object1 = new A();
C* object2 = new B();
Although C pointers, they point to instances of A and B respectively.
Second, your approach is wrong. It seems like you're not taking advantage of polymorphism. If you have functionality that is shared between the classes, it should be implemented in C. If it changes, you should have virtual methods.
Knowledge about the type of an object is usually at least a code smell. You can alter the behavior simply by using polymorphism. Although if it really is necessary, the correct way would be using dynamic_cast:
C* object1 = new A();
A* pA = dynamic_cast<A*>(object1);
pA will be NULL if object1 doesn't point to an object of type A.
This is a design issue in my opinion you have to analyze your problem better. Why do you need to know the type of your object? Why you don't implement the interface method in your A and B classes, which will do whatever you need with a binary data? Take a look on visitor design pattern to get an image of how to implement it in this way.
First off, I know I can not do it, and I think it's not a duplicate questions (this and this questions deal with the same problem, but they only want an explanation of why it does not work).
So, I have a similar concept of classes and inheritance and I would, somehow, elegantly, want to do something that's forbidden. Here's a very simple code snippet that reflects what I want to do:
#include <iostream>
class A{
protected:
int var;
std::vector <double> heavyVar;
public:
A() {var=1;}
virtual ~A() {}
virtual void func() {
std::cout << "Default behavior" << this->var << std::endl;
}
// somewhere along the way, heavyVar is filled with a lot of stuff
};
class B: public A{
protected:
A* myA;
public:
B(A &a) : A() {
this->myA = &a;
this->var = this->myA->var;
// copy some simple data, e.g. flags
// but don't copy a heavy vector variable
}
virtual ~B() {}
virtual void func() {
this->myA->func();
std::cout << "This class is a decorator interface only" << std::endl;
}
};
class C: public B{
private:
int lotsOfCalc(const std::vector <double> &hv){
// do some calculations with the vector contents
}
public:
C(A &a) : B(a) {
// the actual decorator
}
virtual ~C() {}
virtual void func() {
B::func(); // base functionality
int heavyCalc = lotsOfCalc(this->myA->heavyVar); // illegal
// here, I actually access a heavy object (not int), and thus
// would not like to copy it
std::cout << "Expanded functionality " << heavyCalc << std::endl;
}
};
int main(void){
A a;
B b(a);
C c(a);
a.func();
b.func();
c.func();
return 0;
}
The reason for doing this is that I'm actually trying to implement a Decorator Pattern (class B has the myA inner variable that I want to decorate), but I would also like to use some of the protected members of class A while doing the "decorated" calculations (in class B and all of it's subclasses). Hence, this example is not a proper example of a decorator (not even a simple one). In the example, I only focused on demonstrating the problematic functionality (what I want to use but I can't). Not even all the classes/interfaces needed to implement a Decorator pattern are used in this example (I don't have an abstract base class interface, inherited by concrete base class instances as well as an abstract decorator intreface, to be used as a superclass for concrete decorators). I only mention Decorators for the context (the reason I want a A* pointer).
In this particular case, I don't see much sense in making (my equivalent of) int var public (or even, writing a publicly accessible getter) for two reasons:
the more obvious one, I do not want the users to actually use the information directly (I have some functions that return the information relevant to and/or written in my protected variables, but not the variable value itself)
the protected variable in my case is much more heavy to copy than an int (it's a 2D std::vector of doubles), and copying it in to the instance of a derived class would be unnecessarily time- and memory-consuming
Right now, I have two different ways of making my code do what I want it to do, but I don't like neither of them, and I'm searching for a C++ concept that was actually intended for doing something of this sort (I can't be the first person to desire this behavior).
What I have so far and why I don't like it:
1. declaring all the (relevant) inherited classes friends to the base class:
class A{
....
friend class B;
friend class C;
};
I don't like this solution because it would force me to modify my base class every time I write a new subclass class, and this is exactly what I'm trying to avoid. (I want to use only the 'A' interface in the main modules of the system.)
2. casting the A* pointer into a pointer of the inherited class and working with that
void B::func(){
B *uglyHack = static_cast<B*>(myA);
std::cout << uglyHack->var + 1 << std::endl;
}
The variable name is pretty suggestive towards my feelings of using this approach, but this is the one I am using right now. Since I designed this classes, I know how to be careful and to use only the stuff that is actually implemented in class A while treating it as a class B. But, if somebody else continues the work on my project, he might not be so familiar with the code. Also, casting a variable pointer in to something that I am very well aware that it is not just feels pure evil to me.
I am trying to keep this projects' code as nice and cleanly designed as possible, so if anybody has any suggestions towards a solution that does not require the modification of a base class every now and then or usage of evil concepts, I would very much appreciate it.
I do believe that you might want to reconsider the design, but a solution to the specific question of how can I access the member? could be:
class A{
protected:
int var;
static int& varAccessor( A& a ) {
return a.var;
}
};
And then in the derived type call the protected accessor passing the member object by reference:
varAccessor( this->myA ) = 5;
Now, if you are thinking on the decorator pattern, I don't think this is the way to go.
The source of the confusion is that most people don't realize that a type has two separate interfaces, the public interface towards users and the virtual interface for implementation providers (i.e. derived types) as in many cases functions are both public and virtual (i.e. the language allows binding of the two semantically different interfaces). In the Decorator pattern you use the base interface to provide an implementation. Inheritance is there so that the derived type can provide the operation for the user by means of some actual work (decoration) and then forwarding the work to the actual object. The inheritance relationship is not there for you to access the implementation object in any way through protected elements, and that in itself is dangerous. If you are passed an object of a derived type that has stricter invariants regarding that protected member (i.e. for objects of type X, var must be an odd number), the approach you are taking would let a decorator (of sorts) break the invariants of that X type that should just be decorated.
I can't find any examples of the decorator pattern being used in this way. It looks like in C++ it's used to decorate and then delegate back to the decoratee's public abstract interface and not accessing non-public members from it.
In fact, I don't see in your example decoration happening. You've just changed the behavior in the child class which indicates to me you just want plain inheritance (consider that if you use your B to decorate another B the effects don't end up chaining like it would in a normal decoration).
I think I found a nice way to do what I want in the inheritance structure I have.
Firstly, in the base class (the one that is a base for all the other classes, as well as abstract base class interface in the Decorator Pattern), I add a friend class declaration only for the first subclass (the one that would be acting as abstract decorator interface):
class A{
....
friend class B;
};
Then, I add protected access functions in the subclass for all the interesting variables in the base class:
class B : public A{
...
protected:
A *myA;
int getAVar() {return myA->var;}
std::vector <double> &getAHeavyVar {return myA->heavyVar;}
};
And finally, I can access just the things I need from all the classes that inherit class B (the ones that would be concrete decorators) in a controlled manner (as opposed to static_cast<>) through the access function without the need to make all the subclasses of B friends of class A:
class C : public B{
....
public:
virtual void func() {
B::func(); // base functionality
int heavyCalc = lotsOfCalc(this->getAHeavyVar); // legal now!
// here, I actually access a heavy object (not int), and thus
// would not like to copy it
std::cout << "Expanded functionality " << heavyCalc << std::endl;
std::cout << "And also the int: " << this->getAVar << std::endl;
// this time, completely legal
}
};
I was also trying to give only certain functions in the class B a friend access (declaring them as friend functions) but that did not work since I would need to declare the functions inside of class B before the friend declaration in class A. Since in this case class B inherits class A, that would give me circular dependency (forward declaration of class B is not enough for using only friend functions, but it works fine for a friend class declaration).
Hallo,
I come from a C# background and don't have a lot of C++ experience. To produce clean code I try to separate implementation and interfaces and use inheritance when possible. And when I tried to apply typical C# concepts to C++ I ran into a problem that I've been unable to resolve so far. I assume that this is probably trivial for an experienced C++ programmer but it has been driving me crazy for quite a while.
First I declare a base class (it contains no logic at the moment but it will in the future)
class PropertyBase : public IProperty
{
};
Then I define an interface for the Properties
class IProperty
{
public:
virtual ~IProperty() {};
virtual PropertyBase correct(const ICorrector &corrector) = 0;
virtual PropertyBase joinWith(const PropertyBase &partner, const IRecombinator &recombinator) = 0;
};
This is where the problem comes in: The compiler returns errors for the two virtual functions saying that it is not allowed to declare a function that returns an abstract class. Of course I don't want to return an object of the type PropertyBase. I want to declare other classes that inherit from PropertyBase that return an instance of themselves.
Now I've read that a possible way around it is to modify IProperty like this to return pointers:
class IProperty
{
public:
virtual ~IProperty() {};
virtual PropertyBase* correct(const ICorrector &corrector) = 0;
virtual PropertyBase* joinWith(const PropertyBase &partner, const IRecombinator &recombinator) = 0;
};
However I would like to avoid this if possible to prevent memory leaks. It would be great if someone would have a better idea to deal with this problem.
Thank you very much
If you're afraid of memory leaks, switch to smart pointers. That has the additional benefit of being self-documenting wrt. ownership of the returned object.
class IProperty
{
public:
virtual ~IProperty() {};
virtual std::unique_ptr<PropertyBase> correct(const ICorrector &) = 0;
virtual std::unique_ptr<PropertyBase> joinWith(const PropertyBase &,
const IRecombinator &) = 0;
};
In your client code:
std::unique_ptr<PropertyBase> pb(property.correct(corrector));
// use pb and forget about it; smart pointers do their own cleanup
Or, if you want reference counting on the object:
std::shared_ptr<PropertyBase> pb(property.correct(corrector));
See MSDN docs for unique_ptr, shared_ptr.
This may not be the answer you're looking for, but it seems to me that you are a little confused about pointers and values in C++.
You have to return either a pointer, or a reference, in C++ if you want proper ad-hoc polymorphism. In this case, the compiler issued an error, because the base class was abstract. If instantiating an abstract class would be possible, it would have "holes" in it.
The thumb rule is: Whenever you have a class hierarchy, never return objects of such types by value. Suppose you have class Base { int x; }, and class Derived : public Base { int y; }. If you do this:
Base Function() { Derived d; return d; }
...
Base b = Function();
Then b will not be a value of class Derived "hiding behind" a Base. The value b WILL be Base. The compiler will "slice off" the differences between Derived and Base, and put it into b.
In C++, you will have to use pointers or references to facilitate ad-hoc polymorphism. References in C# is pretty much the same thing as pointers in C++, with the exception that you do not have to free the objects in C#, as the garbage collector will handle this for you.
There's nothing wrong with returning a pointer to an object. If you're worried about memory leaks, as you should be, the solution is to use smart pointers to store the returned pointer. The most flexible of these is shared_ptr from boost or the upcoming C++0x standard.
More generally, if you're going to be doing any serious amount of work in C++, getting comfortable with pointers and memory management is kind of essential. For in-depth coverage of that and other tricky aspects of C++, I strongly recommend the Effective C++ books by Scott Meyers and the Exceptional C++ books by Herb Sutter.
There is very easy solution to this problem. Use pointers or references for return values, but instead of returning ownership in the pointers, you should not return ownership.
For example:
class A : public Base
{
public:
Base *correct(const I &c)
{ p2 = do_something(c); return &p2; }
...
private:
A2 p2;
};
What makes this work is that you store the p2 inside the class and never pass ownership of the objects to outside of it. The function in the interface will not create new objects, but instead it'll just return existing one, configured to correct state based on function's parameters. This is a good alternative to the unique_ptr and shared_ptr solution which relies on heap allocation and creating new objects and passing them around.
Now the nice trick with this is that you need to list all possible types you want to return from your correct() function in the data members of the class. For example, if sometimes you would return different type, it'd look like this:
class B : public Base
{
public:
Base *correct(const I &c) {
switch(c.get_bool()) {
case false: p3 = do_something_else(c); return &p3;
case true: p4 = do_something(c); return &p4;
};
}
private:
B3 p3;
B4 p4;
};
But placing your objects p3 and p4 inside the current B object will solve this problem completely.
Consider two classes
class A{
public:
A(){
}
~A(){
}
};
class AImpl : public A{
public:
AImpl(){
a = new AInternal();
}
AImpl(AInternal *a){
this->_a = a;
}
~AImpl(){
if(a){
delete a;
a = null;
}
}
private:
AInternal *a;
};
I am trying to hide the AInternal's implementation and expose only A's interface. Two things I see here
class A is totally empty.
Hiding is achieved basically through inheritance. I have to actually use downcasting and upcasting from A to AImpl and vice versa.
Is this a good design. Being very inexperienced in designing, I cannot see the pitfalls of it and why it is bad?
You're overcomplicating things by using 3 classes. I think what you're looking for is the pimpl idiom.
I am trying to hide the AInternal's implementation and expose only A's interface.
I think you are trying to do something like factory.
Here is an example:
class IA {
public:
IA() {}
virtual ~IA() {}
virtual void dosth() =0;
};
class Factory {
private:
class A : public IA {
public:
A () {}
virtual ~A() {}
void dosth() { cout << "Hello World"; }
};
public:
Factory () {}
virtual ~Factory() {}
IA*newA() { return new A; }
};
And the usage of Factory class:
Factory f;
IA*a = f.newA();
a->dosth();
return 0;
IMO AInternal makes no sense. Whatever you do there, should be done in AImpl. Otherwise, it's ok to do that in C++.
The code is rather obtuse, so I would be concerned with maintaining it six months down the road.
If you're going to do it this way, then the destructor ~A needs to be virtual.
You seem to be combining two common design features:
1) AInternal is a "pimpl". It provides for better encapsulation, for example if you need to add a new field to AInternal, then the size of AImpl doesn't change. That's fine.
2) A is an base class used to indicate an interface. Since you talk about upcasting and downcasting, I assume you want dynamic polymorphism, meaning that you'll have functions which pass around pointers or references to A, and at runtime the referands will actually be of type AImpl. That's also fine, except that A's destructor should either be virtual and public, or non-virtual and protected.
I see no other design problems with this code. Of course you'll need to actually define the interface A, by adding some pure virtual member functions to it that you implemented in AImpl. Assuming you plan to do that, there's nothing wrong with using an empty base class for the purpose which in Java is served by interfaces (if you know Java). Generally you'd have some kind of factory which creates AImpl objects, and returns them by pointer or reference to A (hence, upcasts them). If the client code is going to create AImpl objects directly then that might also be fine, and in fact you might not need dynamic polymorphism at all. You could instead get into templates.
What I don't see is why you would ever have to downcast (that is, cast an A* to AImpl*). That's usually bad news. So there may be some problems in your design which can only be revealed by showing us more of the definitions of the classes, and the client code which actually uses A and AImpl.