C ++, the reason for the constructors

I have two questions.

1) What does the constructor do? What happens if we do not use constructors when declaring an instance?

2) Can you tell me the difference between the two?

A a(1,2)

A *a = new A(1,2)

Sincerely.

+3
source share
5 answers

The constructor initializes the member variables of the class so that it is ready for use. The result of not using the constructor when declaring an instance depends on the context.

If you allocate a variable on the heap, for example:

A *a;

a point to a random address in memory until it is assigned NULL or 0 or an existing or new instance of the class, for example:

A *a = new A(1, 2);

If you allocate a variable on the stack, the following syntax is used:

A a(1, 2); // if parameters are used
A a; // if no parameters are used

a, . , : a , a .

+8

- , . - - . .
++, . ( - ). , Point :

class Point
{
public:
    Point() : x_(0), y_(0) { }
    Point(int x, int y) : x_(x), y_(y) { }
    Point(const Point& p) : x_(p.x), y_(p.y) { }
private:
    int x_;
    int y_;
};

, :

void create_and_destroy_points ()
{
   Point p1; // => x_ = 0, y_ = 0
   Point p2(100, 200); // x_ = 100, y_ = 200
}

Point . , create_and_destroy_points. , p1 p2 .
. , . new , delete. , .

Point* create_point ()
{
   Point* p = new Point(100, 200);
   return p;
}

Point* p = create_point();
// use p 
delete p;

- . , :

Point p1;
Point p2 = p1; // calls the copy constructor for p2 with p1 as argument.
Point p3(p1);  // alternate syntax
+3

# 2, 'a' A , '* a' A. , , . A:: A()

+2

1) ?

:

, ?

, . :

std::string a;

string.

2) ?

A a(1, 2);

.

A a;

.

+2

1) -.

class A {
public:
    A() { a = 0; b = 0; }
    A(int a, int b) { this->a = a; this->b = b; }

private:
    int a;
    int b;
};

, -, .

. , :

A a1;    // uses first constructor, i.e. A::A() 
A a2();  // also uses first constructor

A* a3 = new A(1, 2); // uses second constructor, i.e. A::A(int a, int b) 
A a4(1, 2);          // also uses second constructor

2) :

A a(1, 2)

, , , , , . :

void fn() {
    A a(1, 2);
    ...
    ...
}

when begging for an instance of function a, which will be automatically deleted upon exiting this function.

When:

A *a = new A(1,2)

variable a is declared, and it points to the newly created instance of A. You must manually delete the instance pointed to by the points with "delete a", but your instance can survive the area in which it is declared. For instance:

A* fn()
{
    A *a = new A(1,2)
    return a;
}

here the fn function returns an instance created inside its body, that is, the instance survives the scope.

+2
source

Source: https://habr.com/ru/post/1780997/


All Articles