0

i have the following two classes:

     class MyClass
     {
       friend ostream& operator<<(ostream&, const MyClass& );   
       friend int operator+(const MyClass &, const MyClass &);
       public:
         MyClass(const int );
         MyClass(const int, const int);
         MyClass (const MyClass *,  const MyClass *);
         ~MyClass();
         MyClass& operator++();        
         void printValue();
         void setValue(int);           
         int  getValue() const;
       private:
         int value;     
     };


   class DevClass : public MyClass
   {
     public: 
       DevClass(const int, const char *s); 
       char getId() const;
       void setId(char *s);           

   private:
       char id; 
   };

Implementation of operator++ is the following:

 MyClass& MyClass::operator++() 
  {
   this->value +=1;
   return *this;
  } 

Now, if I use the operator with the derived class:

 DevClass *dev=new DevClass(10,'c');
 ++dev;

"dev" seems to point somewhere else in memory. Why ? Why friend operator are not inherited ? This is a class exercise, so i need to address the problem.
Thank you !.

Discipulos
  • 423
  • 8
  • 23

3 Answers3

4

dev is type DevClass * which is a pointer and not your class. Did you mean ++(*dev)?

Neil Kirk
  • 21,327
  • 9
  • 53
  • 91
3
DevClass dev=new DevClass(10,'c');
 ++dev;

is not legal code. Your compiler should report that as an error.

If you use:

DevClass* dev=new DevClass(10,'c');
 ++dev; // Incrementing the pointer, not the object.

it makes sense that dev points to a different location, though it is cause for undefined behavior since dev points to only one object.

If you use:

DevClass dev = DevClass(10,'c');
 ++dev; // Incrementing the object

dev is the same object before and after the call to operator++().

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • http://stackoverflow.com/questions/14505851/is-the-one-past-the-end-pointer-of-a-non-array-type-a-valid-concept-in-c – Neil Kirk Oct 20 '15 at 16:04
3

In the statement ++dev; you aren't calling operator++ on the object pointed to by dev - you are calling it on dev itself, which is a pointer, and by incrementing it you're making it point to something which is probably invalid. To call operator++ on the DevClass instance, you can use:

++(*dev);
Injektilo
  • 581
  • 3
  • 14