简体   繁体   中英

Why the parameter doesn't change in the class constructor?

Here it is my code. I don't get it why it doesn't print 3, even though in the class constructor param1 becomes 3.

#include <iostream>

using namespace std;

class A{

    int valoare;
public:

    A(int param1 = 3):valoare(param1){}
    int getValoare(){return this -> valoare;}
};

int main()
{

    A vector[] = {*(new A(3)), *(new A(4)), *(new A(5)), *(new A(6))};
    cout << vector[2].getValoare();
    return 0;
}

You might want to read about default arguments: https://en.cppreference.com/w/cpp/language/default_arguments

When you specify an argument for a function with a defualt argument it overrides that default value. Thus, your code will print out 5.

As a side note, your code has a memory leak becuase you allocated memory with the new keyword and never deleted it. You should change the declaration of your Vector, that is, allocate memory on the stack like follows:

Vector = {A(3), A(4), A(5), A(6)}

The element at index 2 in the vector was constructed as A(5) , so it's value ("valoare") is 5. The = 3 in the function definition is a default argument - which is used if you don't specify one yourself. So if you were to write:

std::cout << A().getValoare();

that would print 3 .

But a few more observations are in order:

  1. Prefer English-language names. valoare means "value" in some Latin or European language, right? Romanian perhaps? But - people who don't speak that language won't know that. Since you have to know English to program anyways, that's a safe choice for names.
  2. Try not to use names for variables which are also names of classes in a different namespace. For example, your vector has the same name as std::vector , a class, or rather a class template, in the standard library. Try vec or my_vector or something else that's more distinctive.
  3. You're leaking memory! Why are you using new to create values? Just use the construct, ie

     A vector[] = { A(3), A(4), A(5), A(6) }; 

    is just fine.

  4. More generally, you should avoid calling new and delete explicitly , and instead prefer RAII-style classes - which allocate on construction and deallocate on destruction. The simplest thing to do is to switch to using smart pointers

Why the parameter doesn't change in the class constructor?

It doesn't print the value 3 because you're giving it another value.

from cppreference :

Default arguments are used in place of the missing trailing arguments in a function call:

 void point(int x = 3, int y = 4); point(1,2); // calls point(1,2) point(1); // calls point(1,4) point(); // calls point(3,4) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM