How to Initialize a Const Field in Constructor

How to initialize a const field in constructor?

You need to do it in an initializer list:

Bar(Foo* _foo) : foo(_foo) {
}

(Note that I renamed the incoming variable to avoid confusion.)

initializing const fields in the constructor

This is a great application for C++11 constructor delegation:

class SomeObject {
private:
const std::string some_string;
const int some_int;

public:
// The "real" constructor for SomeObject
SomeObject(std::string str, const int i) :
some_string{std::move(str)},
some_int{i}
{}

// Deserialize from SomeReader (delegates to the primary constructor)
SomeObject(SomeReader& reader) :
SomeObject{reader.get_string(), reader.get_int()} {}

// Deserialize from SomeReader (accepts rvalues,
// delegates to the lvalue constructor)
SomeObject(SomeReader&& reader) :
SomeObject{reader} {}

// Deserialize from named file (delegates to the SomeReader&& constructor)
SomeObject(const char* input_filename) :
SomeObject{SomeReader{input_filename}} {}
};

Initializing C++ const fields after the constructor

You could cast away the constness in the constructor:

class Image {
public:
const int width,height;
Image(const char *filename) : width(0), height(0) {
MetaData md(readDataFromFile(filename));

int* widthModifier = const_cast<int*>(&width);
int* heightModifier = const_cast<int*>(&height);
cout << "Initial width " << width << "\n";
cout << "Initial height " << height << "\n";
*widthModifier = md.GetWidth();
*heightModifier = md.GetHeight();
cout << "After const to the cleaners " << width << "\n";
cout << "After const to the cleaners " << height << "\n";
}
};

That would achieve what you want to do but I must say I personally would stay away from that because it causes undefined behavior according to the standard (excerpt from cppreference)

const_cast makes it possible to form a reference or pointer to
non-const type that is actually referring to a const object ...
Modifying a const object through a non-const
access path ... results in undefined behavior.

I would fear any public data members(at least in regarding your particular example). I would go with Georg's approach or make the data private and provide only the getter.

How to initialize a const field in constructor in typescript?

You can't have a constant class member.

Mainly because class members are always referenced by reference via the this keyword, and that reference can always be changed.

It's not supported in ES6 either.

How to initialize const member requiring computations to be performed?

Use a function call inside a delegating (if avaliable, not neccessarily) constructor's member initialization list:

A::A(std::string const& yourstring) : A(compute_myint(yourstring)) {};

Pass std::string by const&, not just const, while you're at it.

compute_myint can be non-member, static member, possibly not accessible from outside the class, whichever makes the most sense.

Initialize a const field in constructor but first check one parameter

You can use the ternary operator, so that it can be called directly in the constructor initialization list:

class User
{
private:
static int nbUsers;
const int userID;
char* name;

public:
User(int key, char* name) : userID(key == 0 ? -1 : nbUsers++)
{
// ...
}
};

The standard guarantees that only one of the branches will be evaluated, so nbUsers won't be incremented if key == 0.


Alternatively, you can use a helper function:

int initDependingOnKey(int key, int& nbUsers)
{
if(key == 0) return -1;
return nbUsers++;
}

class User
{
private:
static int nbUsers;
const int userID;
char* name;

public:
User(int key, char* name) : userID(initDependingOnKey(key, nbUsers))
{
// ...
}
};

Why can const members be modified in a constructor?

This is not modification (or assignment) but initialization. e.g.

struct Bar {
const int b = 5; // initialization (via default member initializer)
Bar(int c)
:b(c) // initialization (via member initializer list)
{
b = c; // assignment; which is not allowed
}
};

The const data member can't be modified or assigned but it could (and need to) be initialized via member initializer list or default member initializer.

If both default member initializer and member initializer are provided on the same data member, the default member initializer will be ignored. That's why b->b is initialized with value 2.

If a member has a default member initializer and also appears in the member initialization list in a constructor, the default member initializer is ignored.

On the other hand, the default member initializer takes effect only when the data member is not specified in the member initializer list. e.g.

struct Bar {
const int b = 5; // default member initialization
Bar(int c):b(c) {} // b is initialized with c
Bar() {} // b is initialized with 5
};

How to initialize const member variable in a class?

The const variable specifies whether a variable is modifiable or not. The constant value assigned will be used each time the variable is referenced. The value assigned cannot be modified during program execution.

Bjarne Stroustrup's explanation sums it up briefly:

A class is typically declared in a header file and a header file is typically included into many translation units. However, to avoid complicated linker rules, C++ requires that every object has a unique definition. That rule would be broken if C++ allowed in-class definition of entities that needed to be stored in memory as objects.

A const variable has to be declared within the class, but it cannot be defined in it. We need to define the const variable outside the class.

T1() : t( 100 ){}

Here the assignment t = 100 happens in initializer list, much before the class initilization occurs.

How to use const in C# class constructor

You can't. By definition, consts in C# are defined at compile-time, not at runtime. They can't be changed by any code, even constructor code, because they're not even there at runtime - they're replaced by their literal values at every point of usage.

What you're looking for is either readonly fields or read only properties.

  1. Readonly fields are marked by the readonly modifier:

    private readonly string _username;

    Readonly fields are only assignable during construction, either directly assigned in the definition itself (readonly string _username = "blah") or in the constructor. The compiler will enforce this limitation, and will not allow you to set a value anywhere else.

  2. Readonly properties are simply properties that don't expose a setter at all. Until C# 6, you could use them to return the value of a readonly field (as above), but you couldn't assign to them. As of C# 6, though, there's syntax supporting read-only auto-properties that can be assigned: even though there's no explicit setter, there's an implicit setter that can, again, only be called from the constructor, or from a field initializer:

    public string Username { get } = "Username";

    It may look strange that you're setting to a property with no setter, but that's simply an implicit part of the language - there's an implicit backing field that's readonly, and can be set at initialization.



Related Topics



Leave a reply



Submit