Weird constructor in C ++ class

I have an exam on Saturday, and I am looking through past documents, and I came across a question according to C ++ code:

class Car {
     char *LicencePlate;
     int age;
public:
     Car(const Car &); //this declaration
     ~Car();
}

What is the purpose of the ad on line 5? In general, what functionality should implement such a declaration? Write the code needed to implement the announcement in line 5, as it will be displayed in the file Car.cpp, taking into account the information provided.

+5
source share
5 answers

Skip this one.

As you can say on behalf of, this is a constructor. Since the parameter accepts a reference to an object of the same type, this is a copy constructor (C ++ nomenclature).

( ), , . .

:

class Car {
     char *LicencePlate;
public:
     Car(char* plate, int size)
     {
        LicencePlate = new char[size];
        strcpy(LicencePlate, plate);
     }
     ~Car()
     {
        delete[] LicencePlate;
     }
};

, . . LicencePlate. , . , :

Car a("abc",3);

:

Car b(a);

, . , , a.LicencePlate == b.LicencePlate. - ?

a , a.LicencePlate . undefined, b , b destructor (, , ).

, :

class Car {
     char *LicencePlate;
     int sz;
public:
     Car(char* plate, int size)
     {
        LicencePlate = new char[size+1]();
        strcpy(LicencePlate, plate);
        sz = size;
     }
     Car(const Car& other)
     {
        LicencePlate = new char[other.sz+1]();
        sz = other.sz;
        strcpy(LicencePlate, other.LicencePlate);
     }
     ~Car()
     {
        delete[] LicencePlate;
     }
};

, ( ). , , :

Car a("abc",3);
Car b;
b = a; //assignment - operator= is called

. b , , .

, , .

+9

, , .

, , .

+8

. Car, , , ( ) . . , strdup .

+2

. .

:

Car(const Car &)

"const" , . "& ;" , . "&" (pass by value) . , , , , .

The code included in the cpp file should make an acceptable copy of the transferred instance. Valid in the sense that makes sense based on a user script.

0
source

I assume you mean line 5, then

Car(const Car &);

- a constructor whose only argument is a reference to another Car object. It is marked as const to indicate that the designer should not modify this vehicle. Since this is a link, you need to check to make sure that you do not have any link to the same object that is being created:

if (this==car){
  return;
}

Or something like that.

-3
source

All Articles