Reputation: 1537
I trying to reproduce the Bridge pattern from Java book, but getting stuck with pointers dilemma cause I'm novice. I threw away includes and part the of implementation, because it's just printf's over there:
// main.cpp
int main () {
DrawApi *rc = new RedCircle();
Circle redCircle = new Circle(rc);
redCircle.draw();
}
// DrawApi.h
class DrawApi
{
public:
virtual void drawCircle() = 0;
};
// Shape.h
class DrawApi;
class Shape
{
protected:
DrawApi *drawApi;
public:
Shape(DrawApi *mDrawApi) : drawApi(mDrawApi) {}
virtual void draw() = 0;
};
// Circle.h
class Circle : public Shape {
public:
Circle(DrawApi *mDrawApi) : Shape(mDrawApi) {}
void draw();
};
After compile and run a get an error:
$ g++-5 -std=c++14 -g main.cpp RedCircle.cpp Circle.cpp && ./a.out && rm a.out
main.cpp: In function ‘int main()’:
main.cpp:7:46: error: conversion from ‘Circle*’ to non-scalar type ‘Circle’ requested
Circle redCircle = new Circle(rc);
Shape ctor is waiting for pointer to DrawApi but seems gets an object. I thought I declared rc variable as pointer to DrawApi.
Upvotes: 1
Views: 106
Reputation: 2222
Circle redCircle = new Circle(rc);
If you want to initialise (copy construct) a Circle
from Circle *
, you need a constructor, say Circle(Circle *)
.
I guess that, in fact, you just want to initialise a Circle
from rc
. Since rc
is DrawApi *
, and Circle
has a constructor which takes DrawApi *
as argument, a.k.a Circle(DrawApi *mDrawApi)
. You can simply write:
Circle redCircle(rc);
redCircle.draw();
If I was wrong, then maybe:
Circle *redCircle = new Circle(rc);
redCircle->draw();
I prefer the first version for two reasons:
DrawApi
has a virtual member function too, and you have already
conducted a Derived-to-Base conversion.BTW, your program has some serious memory management issues. Having them solved before go any further will be a good choice. (Smart pointer will help you a lot)
There are subtle differences between Type obj(x)
and Type obj = x
.
Upvotes: 1