Hani Goc
Hani Goc

Reputation: 2441

Copy Constructor Pointer Object

I have the following class with the 2 pointers to block

#ifndef SCORING_H
#define SCORING_H

#include "Block.h"
#include <iostream>
#include <vector>
#include <cstring>

using namespace std;

class Scoring
{
    public:
        Scoring(Block *, Block*, string, string, double);
        virtual ~Scoring();
        Scoring(const Block& b1, const Block &b2);
    private:
        Block * b1;
        Block * b2;
        string path1;
        string path2;
        double val;
};

#endif // SCORING_H

Class Block is the following:

class Block {
    public :
        ///constructo
        Block(double, double, double, double, int, vector<LineElement*>);

        ///Setter functions
        void setID(int);
        void setTop(double);
        void setLeft(double);
        void setRight(double);
        void setBottom(double);
        void setLine(vector<LineElement*>);

        int getID();
        double getTop();
        double getLeft();
        double getBottom();
        double getRight();
        vector<LineElement*> getLine();

    private:
        int id;
        vector<LineElement*> Listline;
        double top;
        double left;
        double bottom;
        double right;
};

#endif // ELEMENT_H_INCLUDED

I want to know, Should I construct a copy constructor for "Block * b1;Block * b2" and how can I treat these 2 points in the class scoring.h?

Thank you.

Upvotes: 0

Views: 2363

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409136

If you create a constructor other than plain and simple Block::Block(const Block&) then it's not a copy-constructor. If you want to make a constructor in Scoring taking two Block pointers it's most definitely is not a copy-constructor.

If you want a copy-constructor in Scoring it should be like this:

class Scoring
{
    // ...

    Scoring(const Scoring& other);

    // ...
};

Then in that constructor you copy from other:

Scoring::Scoring(const Scoring& other)
    : b1(new Block(*other.b1)),
      b2(new Block(*other.b2)),
      path1(other.path1),
      path2(other.path2),
      val(other.val)
{
}

Of course, you should probably make a copy-constructor for the Block class too, as it contains a vector of pointers, and if you don't you will have two vectors with pointers pointing to the same objects, and that will be bad when you delete these objects in one vector but not the other.

Upvotes: 1

Related Questions