DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C++ (http://www.daniweb.com/forums/forum8.html)
-   -   about reference of a instance in class (http://www.daniweb.com/forums/thread112548.html)

havec Mar 6th, 2008 5:57 pm
about reference of a instance in class
 
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?:@

vijayan121 Mar 6th, 2008 8:19 pm
Re: about reference of a instance in class
 
> 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.


All times are GMT -4. The time now is 6:41 am.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC