invalid constructor call

i have a class myClass that has 3 constructors defined for it
1
2
3
4
5
6
7
8
9
//myClass constructors
//default constructor
myClass();
//copy constructor
myClass(myClass& );
//other constructor
myClass(string name, int user);
myClass(int id);

i am trying to create an object of myClass using myClass::myClass(int id) like so
1
2
int id = 0;
myClass test = myClass(id);

how ever when i build the program the compiler says
 error: no matching function for call to 'myClass::myClass(myClass)'
candidates are: myClass(int) , myClass(myClass &);

any idea how i can forcefully call myClass::myClass(int)without defining myClass::myClass(myClass) ?
you copy constructor is ill formed. It should be:

myClass(const myClass&); // <- note the 'const'

Edit:

You should fix that, but another way to sidestep this problem would be to call the desired ctor directly instead of copying from a temp object:

1
2
3
// myClass test = myClass(id);  // instead of this
myClass test(id);  // do this
myClass test = id;  // or this 


But fix the 'const' thing too.
Last edited on
the reason my copy constructor isnt defined like:
myClass(const myClass&)
is because myClass is a derived class for baseClass which is and abstract class defined as so:
1
2
3
4
5
6
7
8
9
10
class baseClass{
public:
    int getID(int pos);
    void setID(int pos, int val);
    //... more member fucntions
private:
    int ids[];
   //..more private members

};

and in the copy constructor for myClass i am copying the values for baseClass::ids like so
1
2
3
4
5
myClass(myClass& ){
    for(int i =0; i <3; ++i){
              this->setID( i , p.ID(i));
        }
}

but when i had the copy constructor defined as myClass(const myClass&) , my compiler told me
myClass.cpp:25: error: passing 'const myClass' as 'this' argument of 'int baseClass::ID(int)' discards qualifiers
which i didnt know how to fix without removing the const specifier.
if you could tell me how i can get around this that would be great. and your other solution worked just fine.
The problem with that is that myClass(myClass&) isn't a copy constructor. You need the const to make it the copy constructor.

Your problem might be just that your class isn't const correct. getID, for example, should probably be a const function:

 
int getID(int pos) const;  // <- note the const 
thanks that fixed it
Topic archived. No new replies allowed.