Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Class Contructor setting Variables whats the difference between those tho ways?

first here is the example Code:

cPerson.h:

#pragma once
class cPerson
{
public:
    cPerson();
    ~cPerson();
    int Age;
};

cPerson.cpp

#include "cPerson.h"

cPerson::cPerson()
{
    this->Age = 3; // Way 1
    cPerson::Age = 4; // Way 2
}

cPerson::~cPerson() { }

Ok now my Question:

If we are defining a new Class in C++ there are two ways to set the initial Values. There is (Way 1) by using the "this"-pointer, or (Way 2) using the scope operator ( :: ). In school I learned it using "this->". Now, years after not using C++, I startet to get into it again and found this second way, using the scope operator. Both way work fine BUT what's the exact difference between them and what's the "faster"/"better" way? I'm that kind of guy who likes to know what exactly is going on in my ram/cpu if I'm programming.

So I hope someone can help me out, and thanks in advance.

like image 660
Phillip Avatar asked Dec 10 '25 11:12

Phillip


1 Answers

A better way to write the constructor as

cPerson::cPerson() : Age(3)
{
}

since then you can construct a const instance of your object. Consider starting Age with a lower case letter: this would be more conventional.

You could refine your first way by writing the more succinct Age = 3;: sometimes initialising members in the constructor body is unavoidable if they depend on the result of complex calculations.

Using :: is idiosyncratic: using the scope resolution operator will fail if the member is defined in a base class. But it does have occasional usage, particularly if you need to disambiguate a shadowed base class member.

Finally, from C++11 onwards you could simplify your class to

struct cPerson
{
    int Age = 3;
};

See C++11 allows in-class initialization of non-static and non-const members. What changed?

like image 122
Bathsheba Avatar answered Dec 12 '25 01:12

Bathsheba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!