Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
4.50/5 (2 votes)
See more:
Hi All,

In my application i've 2 classes, a Base one (callaed Categorie) and a derived one (called CAT1). I create a vector of my custom class CAT1 and i tried to fill that vector with CAT1 elements using the push_back function:

Below are the declaration of my classes :

[Base Class]
C#
class Categorie
{
    //Attributs
public:
    int ID;
    string Fournisseur;
    int Min;
    int Quantite;
    float Prix_Vente;
    //Constructeurs
public:
    Categorie(int ID, string Fournisseur, int Min, int Quantite, float Prix_Vente)
    {
        this->ID = ID;
        this->Fournisseur = Fournisseur;
        this->Min = Min;
        this->Quantite = Quantite;
        this->Prix_Vente= Prix_Vente;
    }

    Categorie(const Categorie & CSrc)
    {
        this->ID = CSrc.ID;
        this->Fournisseur = CSrc.Fournisseur;
        this->Min = CSrc.Min;
        this->Quantite = CSrc.Quantite;
        this->Prix_Vente= CSrc.Prix_Vente;
    }
};

[End Base Class]

[Derived Class]
C#
class CAT1: public Categorie
{
    //Attributs
public:
    string Utilite;
    //Constructeurs
    CAT1(int ID, string Fournisseur, int Min, int Quantite, float Prix_Vente, string Utilite):
        Categorie(ID,Fournisseur, Min, Quantite, Prix_Vente), Utilite(Utilite){}

    CAT1(const CAT1 & CSrc) : Categorie(CSrc), Utilite(CSrc.Utilite){}

};


[End Derived Class]

And here the lines that i wrote to fill the vector with elements if CAT1:
C#
CAT1 * instance;
instance = AjoutCAT1(); // declared CAT1* AjoutCAT1(){...}
CAT1Vct.push_back(instance);


When Compiling i got this error :

error C2664: 'push_back' : cannot convert parameter 1 from 'class CAT1 *' to 'const class CAT1 &'<br />



what's wrong and how fix it ?

Thank you.
Posted

1 solution

It looks like your CAT1Vct is declared as
C++
std::vector<CAT1> CAT1Vct;


but to work with pointers it should be
C++
std::vector<CAT1*> CAT1Vct;


Hope this helps,
Fredrik
 
Share this answer
 
Comments
Schehaider_Aymen 19-Apr-12 10:47am    
That's true, your help is well appreciated. Thank you, it works fine.
Fredrik Bornander 19-Apr-12 11:19am    
Glad I could help.
You could also use your current declaration but change the way you push them on to the vector to this;
CAT1Vct.push_back(*instance);.
JackDingler 19-Apr-12 16:49pm    
You need to take care with this technique as std::vector<cat1> will attempt to copy any member you push to it. So all members will be of class type CAT1, and you'll need a copy constructor for other class types.

Whereas std::vector<category *=""> will allow you to push pointers to both Category and CAT1 objects (and any other classes derived from category).

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900