Start New Discussion within our Software Development Community

I want to disign a class, which can include a reference of a instance. But the class of this instance is not confirm. In java I can use "object" class, because "object" class is father class of all class. for example
class XX{
...
...
private object YY;
...

public void setYY(object y){YY = y}
public object getYY(){return YY}
}
use setYY I can give XX a reference of a instance, and use getYY to receive it. I dont need care of the class of this instance, because object is "TOP-Father-class".

But in C++ how can I do that?:@

> In java I can use "object" class, because "object" class is father class of all class.
C programmers use void* where java programmers use object . you cannot use either without a cast; a wrong cast will result in unpleasant consequences in both. in C, incorrect runtime behaviour (seg fault etc.), in java an exception being thrown.
if object is the father, void* is the grandfather.

the solution in C++ depends on the paradigm that you want to use:
generic programming (typesafe):

template< typename T > class XX
{
   // ...
   private: T yy ;
   public:
      void setYY( const T& y ) { yy = y ; }
      const T& getYY() const { return yy ; }
      T& getYY() { return yy ; }
   // ...
};

object oriented programming (not so typesafe):
have a base class (say object) which all objects which can be put into an XX must inherit from.

struct  /* __declspec(novtable) */ object
{
   virtual ~object() = 0 { /* empty */ }
};
class XX
{
   // ...
   private: object* yy ;
   public:
      void setYY( object* y ) { yy = y ; }
      const object*getYY() const { return yy ; }
      object* getYY() { return yy ; }
   // ...
};

to use the object that is retrieved, a cast is required. in C++, this would be a dynamic_cast which may fail at runtime. this would mimic java fairly closely.

This article has been dead for over six months. Start a new discussion instead.