the default constructor of union cannot be referenced -- it is a deleted function

I don't understand where I'm wrong at my code O.o.

class Object {

private:

std::string name;

Shape shape;//union

public:

Object() = default;

Object(std::string object_name, Rectangle object_rectangle) {
//error
name = object_name;

shape.rectangle = object_rectangle;

}

};
Can you show us the Shape structure? Rectangle structure will also do.
union Shape {

Shape_Type type;

Rectangle rectangle;

Circle circle;

};

class Rectangle {

private:

sf::RectangleShape rectangleshape;

public:

Rectangle() = default;

Rectangle(float width, float height) : rectangleshape(sf::RectangleShape(sf::Vector2f(width, height))) {}

void setPosition(float position_x, float position_y) {

rectangleshape.setPosition(position_x, position_y);

}

void setAngle(float angle) {

rectangleshape.setRotation(angle);

}

sf::RectangleShape* getRectangleShape() {

return &rectangleshape;
}

Position getPosition() {

return Position(rectangleshape.getPosition().x, rectangleshape.getPosition().y);
}

};
Why do you use Union structure?
If anything, you should use virtual inheritance.
http://www.cplusplus.com/doc/tutorial/polymorphism/
Well how do you think i can call .setPosition from Rectangle/Circle from Object instance?
You can just use struct Shape and it will work. Just one more variable to determine which type of structure you should use.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const int SHAPE_UNDEFINED = 0;
const int RECTANGLE_TYPE = 1;
const int CIRCLE_TYPE = 2;

struct Shape
{
    Shape() {shapeType = SHAPE_UNDEFINED;}

    Shape_Type type;
    Rectangle rectangle;
    Circle circle;

    int shapeType;
};


And...
1
2
3
4
5
6
Object(std::string object_name, Rectangle object_rectangle)
{
    name = object_name;
    shape.rectangle = object_rectangle;
    shape.shapeType = RECTANGLE_TYPE;
}


There are definitely some other ways to do it. For example, you can make use of class inheritance.
Last edited on
I was trying to make it with inheritance. But I was having a big problem. How do I call from Object Rectangle's setPosition function.

If Object is Base class and Rectangle and Circle are Derived classes.
If Object is Base class and Rectangle and Circle are Derived classes.

You have to use virtual inheritance if that's the case.
Last edited on
Topic archived. No new replies allowed.