Using Pure Virtual Functions

Here is my code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
//Pure virtual functions and interfaces in c++

#include<iostream>
using namespace std ;

class Figure { 
	protected :
		float dim1 ;
		float dim2 ;
		
	
		Figure(float d1 = 0 ,float d2 = 0) : dim1(d1) , dim2(d2) 
		{
		
		}
		
	public :
		virtual float getArea() = 0 ;
};

class Triangle : public Figure {
	public :
		Triangle(float base = 0, float height = 0) : Figure(base,height){
		}
		
		virtual float getArea(){
			cout << "Triangle " ;
			return (1/2) * dim1 * dim2 ;
		}
};

class Rectangle : public Figure {
	public :
		Rectangle(float length = 0, float breadth = 0): Figure(length,breadth){
	
		}
		
		virtual float getArea(){
			cout << "Rectangle " ;
			return dim1*dim2 ;
		}
};

int main(int argc , char ** argv){
	Rectangle rect(20,30) ;
	Figure &fig = rect;
	cout << "Area of Rectangle " << fig.getArea() << endl;
	Triangle tri(10,10) ;
	fig = tri ; //I guess the error is in this line but what ?
	cout << "Area of Triangle " << fig.getArea() <<endl;
	return 0;
}


Output:
1
2
Rectangle Area of Rectangle 600
Rectangle Area of Triangle 100 // Triangle::getArea() never executes  


The output is wrong. Any suggestions will be appreciated. Thanks

The object that a reference is referring to is set when the reference is created and it's not possible to change it later. fig = tri ; This will assign tri to rect using Figure's copy assignment operator.
I'm surprised you aren't getting a compiler error/warning, a reference can only be initialized once. Once it has been set, it cannot be re-assigned, for lack of a better word.
¿Why should be a warning/error? it's just copying two figures...

Btw return (1/2) * dim1 * dim2 ; integer division returns an integer, so 0
I read it as....

Figure &fig = rect; and
fig = &tri
then how should I use it ?
Sample code
1
2
3
Figure *fig ;
fig = &rect ; //for rectangle
fig = &tri ; // for triangle 
then how should I use it ?


No, this results in the error I stated in my first post, a reference can be initialized once and only once. If what you need to refer to changes then you use a pointer.

I almost did it again, just quickly looked at your code without reading it (thought the * was a &). Yes, you can do it like that and it will work.


The original problem you saw:
The problem you are seeing is 'splicing', you initialize the reference with an object of type Rectangle. Then you copy assign a Triangle to an already seated reference. When you call the virtual function getArea() it uses the vtable associated with the Rectangle, hence 10*10 = 100 and not your expected 50.
thanks a lot for the explanation @clanmjc
Topic archived. No new replies allowed.