Link to home
Start Free TrialLog in
Avatar of Gsteingr
Gsteingr

asked on

C++ - Why does my class constructor cause this error? 'Point3' : no copy constructor available or copy constructor is declared 'explicit'

Hi,

I got this strange error the other day. When I isolated it, (made an empty project with nothing else in it), I found out that it only comes when using the following (Point3) class constructor.

a) If I comment out the constructor "Point3(Point3 &b) {...}" , then "myVector.push_back(p3);" works fine. Otherwise I get this error.

Im very puzzled why this is happening. Any ideas?

Thank you.

************ Main.cpp***********
#include <iostream>
#include <vector>
#include "Point3.h"

using namespace std;

void main(int argc, char** argv)
{
      vector<Point3> myVector;
      Point3 p3;
      myVector.push_back(p3);  
}
******************************
************ Point3.cpp***********
#ifndef      point3_h
#define point3_h

class Point3
{
      public:
            Point3(){ x = 0.0f;y = 0.0f;z = 0.0f;}                    // constructor 1
            // Point3(Point3 &b) {x = b.x; y=b.y; z=b.z;}    // constructor 2 - ONLY COMPILES IF THIS LINE IS COMMENTED OUT !!
            float x,y,z;
};

#endif
******************************
Avatar of Gsteingr
Gsteingr

ASKER


Sorry,

************ Point3.cpp***********

should be

************ Point3.h***********
vector class internally uses copy constructor to create it's own copy of class instance. I confess that I don't understand completely C++ explicit constructors mumbo-jumbo, but at least I know simple fix for this problem:

    Point3(const Point3 &b)            // add const keyword
    {x = b.x; y=b.y; z=b.z;}

I know what to do, but I don't know why does this happen. Hopefully, somebody else can explain this :)

Wow, it worked. Thanks a lot.

Does anybody know how the Vector is stored in memory. Would the Vector stored these two the same way:

Point3 p1;                                // Created on the Stack
Point3 *p2 = new Point3();       // Created on the Heap

myVector.push_back(p1);
myVector.push_back(*p3);
ASKER CERTIFIED SOLUTION
Avatar of AlexFM
AlexFM

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial