The following is quite long but ignore the class declarations. Im confused about the address assignments to the object pointers in main()
Code:
#include <iostream>
#include <cstring>
using namespace std;
class twodshape {
double x,y;
char name[20];
public:
virtual double area() {
cout<<"Must be redefined."<<endl;
return 0.0;
}
double X() { return x; }
double Y() { return y; }
void X(double a) { x=a; }
void Y(double a) { y=a; }
twodshape(double a,double b,char *str) {
x=a;
y=b;
strcpy(name,str);
}
};
class rectangle : public twodshape {
bool sqr;
public:
double area() {
return X()*Y();
}
rectangle(double a,double b):twodshape(a,b,"rectangle") {
if(a==b) sqr=true;
}
bool Sqr() { return sqr; }
};
int main() {
twodshape *obs[3];
obs[0]=&rectangle(10,10); //here (isn't this the same as saying p=&5 instead of p=&var)
obs[1]=&rectangle(5,15); //and here
obs[2]=&twodshape(7,8,"generic"); //and here
cout<<"Shape 1 area: "<<obs[0]->area()<<endl;
cout<<"Shape 2 area: "<<obs[1]->area()<<endl;
cout<<"Shape 3 area: "<<obs[2]->area()<<endl;
return 0;
}
First time I saw it I dismissed it as wrong, but decided to try compiling it anyway. But it actually worked. What I dont understand is how a pointer can be assigned to an object that isnt even declared properly. Or is there something I missed out...