Why does aggregate initialization not work when there is virtual function?

131 Views Asked by At

I could no longer use aggregate initialization after introducing a virtual function to my struct:

error C2440: 'initializing': cannot convert from 'initializer list' to 'Point_3

Aggregate initialization is much more convenient than manually assigning to each struct member:

A.x = 100;
A.y = 100;

Is there a way around that error? Here's an example code:

#include <iostream>

struct Point_1 {
    int x;
    int y;

    void foo() {
        std::cout << "x: " << x << std::endl;
        std::cout << "y: " << y << std::endl;
    }
};

struct Point_2 {
    int x;
    int y;

    virtual void foo() {}
};

struct Point_3 : Point_2 {
    void foo() override {
        std::cout << "x: " << x << std::endl;
        std::cout << "y: " << y << std::endl;
    }
};

int main() {
    Point_1 A = { 100, 100 };
    A.foo();

    Point_3 B = { {200, 200} }; // error here
    B.foo();

    return 0;
}
0

There are 0 best solutions below