Inheritance and STL vector

113 views Asked by At

let's say i got a class "Simple" with this private var : std::vector m_listePoint; which constructor is

Simple(EnumCouleur::tEnumCouleur c,vector<Point> listeP);

(couleur is inherited from her mother class)

i got another class which is "Circle" ( a child class of "Simple"), with 2 vars : 1 Point, 1 radius Here is the constructor i ve tried :

Cercle::Cercle( const Point centre, const double rayon, EnumCouleur::tEnumCouleur v)
{
        m_rayon = rayon;
        vector<Point> liste;
        liste.push_back(centre);
        __super::Simple(v,liste);

}

I got an error saying Simple doesnt have a default constructor.

I know that basically i should do this way :

 Cercle::Cercle( const Point centre, const double rayon, EnumCouleur::tEnumCouleur v) : m_rayon(rayon), Simple(...)

the problem is : how to build the vector then?

This might be a stupid question i don't know, i come from java, this is why i used super and might be bad way...

2

There are 2 answers

2
T.C. On BEST ANSWER

Use the vector constructor that makes a vector of n copies of an element:

Cercle::Cercle( const Point centre, const double rayon, EnumCouleur::tEnumCouleur v) 
       : m_rayon(rayon), Simple(v, std::vector<Point>(1, centre)) { /* ... */ }

Or, in C++11, use the initializer list constructor:

Cercle::Cercle( const Point centre, const double rayon, EnumCouleur::tEnumCouleur v) 
       : m_rayon(rayon), Simple(v, {centre}) { /* ... */ }
1
Mooing Duck On

Vector has a useful constructor here: vector(size_type count, const T& value, <irrelevent>) that makes it easy to construct a vector with a single element: vector<Point>(1, centre).

Like so:

Cercle::Cercle( const Point centre, const double rayon, EnumCouleur::tEnumCouleur v)
    :m_rayon(rayon),
    Simple(v, vector<Point>(1, centre))
{
}

If you have multiple elements, make a simpler helper function or use an initializer_list

initializer_list

Rect::Rect( const Point topleft, const Point botright, EnumCouleur::tEnumCouleur v)
    :m_rayon(rayon),
    Simple(v, {topleft, botright})
{
}

helper function:

std::vector<Point> make_from_two(point one, point two) {
    vector<Point> liste;
    liste.push_back(one);
    liste.push_back(two);
    return liste;
} 

Rect::Rect( const Point topleft, const Point botright, EnumCouleur::tEnumCouleur v)
    :m_rayon(rayon),
    Simple(v, make_from_two(topleft, botright))
{
}