Reputation: 2035
#include <iostream>
using namespace std;
class Shape
{
public:
virtual void draw()=0;
};
class Circle:public Shape
{
public:
void draw(){cout<<"circle "<<endl;}
};
class Rectangle:public Shape
{
public:
void draw(){cout<<"Rectangle "<<endl;}
};
I want to Create a Picture class where i can draw diffrent shapes. I am passing Shape class pointer (Abstract) in Picture class Constructor like that:
class Picture
{
public:
Shape* s1;
Picture(Shape *fp): s1(new Shape){}
void PictureDrawn()
{
s1->draw();
}
};
int main()
{
Circle cir;
Picture pic(cir);
pic.PictureDrawn();
}
I am getting compilation error . Please can any one explain how to write the Picture class constructor correctly so I can make different shapes ?? Thanks
Upvotes: 2
Views: 1069
Reputation: 145279
If you want to copy the dynamically allocated shape, make it cloneable (→ FAQ link).
That means, add a method virtual Shape* clone() const = 0
.
Implement it in every concrete class derived from Shape
.
The most practical way to automate the implementation of clone
, is IMHO to define a macro.
But since young readers have a history of reacting badly to any suggestion of defining a macro, let me add that that in C++11 an alternative is to use the Curiously Recurring Template Pattern for the clone
implementation (because C++11 supports argument forwarding), and that in C++98 there is yet another, but rather complex!, alternative, based on dominance in an inheritance hierarchy.
However, having said all that, let me again suggest the macro, or simply writing the same implementation (sans name variation) in every class.
Upvotes: 0
Reputation: 10940
class Picture
{
public:
Shape* s1;
Picture(Shape *fp): s1(fp){}
void PictureDrawn()
{
if(s1 != NULL)
s1->draw();
}
};
int main()
{
Circle cir;
Picture pic(&cir);
pic.PictureDrawn();
}
Upvotes: 1
Reputation: 3918
If I understand correctly, your abstract class shape is an interface since all it's method are pure virtual. Having said that, you can't instantiate an interface. You'd have to "declare" non-virtual pure method or pass in a pointer to to your class.
Upvotes: 0
Reputation: 1516
you can't do
new Shape
That is an attempt to instantiate the abstract class. I think what you want to do is:
Picture(Shape *fp): s1(fp){}
This will assign the argument to the s1 variable which is I think what you intended.
Also note that your code at the bottom isn't correct either. You've declared the Picture constructor as taking a pointer to a Shape, but then you're passing in the Circle by value. What you want is.
Circle cir;
Picture pic(&cir);
Or, change the Picture class so it uses a reference instead of a pointer.
Upvotes: 9