Reputation: 279
I have this program in c++.
ref2.h :
#ifndef REF2_H
#define REF2_H
#include <iostream>
using std::cout;
using std::endl;
int add_int_int(int a, int b) {return (a+b);}
class IntClass;
class Number {
public:
//return a Number object that's the results of x+this, when x is IntClass
virtual Number& addInt(IntClass& x) = 0;
//Print the number stored in the object
virtual void print_number() = 0;
}
class IntClass : public Number {
private:
int my_number;
public:
//Constructor
IntClass(int n):my_number(n) {}
//returns the number stored in the object
int get_number() {return my_number;}
//print the number stored in the object
void print_number() {cout << my_number << endl;}
Number& addInt(IntClass& x);
}
Number& IntClass::addInt(IntClass& x)
{
int n = add_int_int(my_number, x.get_number());
IntClass elem = IntClass(n);
IntClass &ref = elem;
return ref;
}
#endif
test.cpp
#include "ref2.h"
#include <iostream>
using std::cout;
using std::endl;
int main() {
cout << "Testing subtyping polymorphism:" << endl;
IntClass ia(1);
IntClass ib(2);
Number& num = ia.addInt(ib); num.print_number(); //should be: 3
}
I don't find my mistake. If any one can help me ?
Upvotes: 1
Views: 1251
Reputation: 21357
The concept of returning a reference to a Number is (in this case) flawed. Think of a reference like a pointer. The function IntClass::addInt is allocating a new IntClass object on the stack, then returning a reference to it.
When the function returns, the memory for the IntClass is freed, so the reference points to garbage.
You should be returning a pointer to a Number (Number*), and you will need to use new IntClass
to create one. Then you will also need to call delete
on it when you finish using it.
Upvotes: 3
Reputation: 25690
You're returning a reference to a local variable in addInt(). Don't do that. The compiler should've warned you about it.
Upvotes: 5
Reputation: 340366
You're returning a reference to a local object that goes out of scope when addInt()
returns:
IntClass elem = IntClass(n);
IntClass &ref = elem;
return ref;
Upvotes: 1