about reference of a instance in class

Please support our C++ advertiser: Intel Parallel Studio Home
Reply

Join Date: Mar 2008
Posts: 1
Reputation: havec is an unknown quantity at this point 
Solved Threads: 0
havec havec is offline Offline
Newbie Poster

about reference of a instance in class

 
0
  #1
Mar 6th, 2008
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?
Last edited by havec; Mar 6th, 2008 at 5:58 pm.
Reply With Quote Quick reply to this message  
Join Date: Dec 2006
Posts: 1,089
Reputation: vijayan121 is a name known to all vijayan121 is a name known to all vijayan121 is a name known to all vijayan121 is a name known to all vijayan121 is a name known to all vijayan121 is a name known to all 
Solved Threads: 164
vijayan121 vijayan121 is offline Offline
Veteran Poster

Re: about reference of a instance in class

 
0
  #2
Mar 6th, 2008
> 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):
  1. template< typename T > class XX
  2. {
  3. // ...
  4. private: T yy ;
  5. public:
  6. void setYY( const T& y ) { yy = y ; }
  7. const T& getYY() const { return yy ; }
  8. T& getYY() { return yy ; }
  9. // ...
  10. };
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.
  1. struct /* __declspec(novtable) */ object
  2. {
  3. virtual ~object() = 0 { /* empty */ }
  4. };
  5. class XX
  6. {
  7. // ...
  8. private: object* yy ;
  9. public:
  10. void setYY( object* y ) { yy = y ; }
  11. const object*getYY() const { return yy ; }
  12. object* getYY() { return yy ; }
  13. // ...
  14. };
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.
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:



Other Threads in the C++ Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC