Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#'s default keyword equivalent in C++?

Tags:

c++

c#

default

In C# I know you can use the default keyword to assign default values as 0 to value types and null to reference types and for struct types individual members are assigned accordingly. To my knowledge there are no default values in C++. What approach would you take to get the same functionality as the default keyword for Generics while programming in C++?

like image 423
vinayvasyani Avatar asked Sep 12 '10 01:09

vinayvasyani


2 Answers

Assuming the type is default-constructible, you can use value initialization. For example,

template <typename T>
T get()
{
    return T(); // returns a value-initialized object of type T
}

If the type is not default-constructible, typically you need to provide a default to use. For example,

template <typename T>
T get(const T& default_value = T())
{
    return default_value;
}

This function can be called with no argument if the type is default-constructible. For other types, you can provide a value to be returned.

like image 159
James McNellis Avatar answered Sep 20 '22 21:09

James McNellis


C++ doesn't have the default keyword, because it doesn't have the distinction between reference and value types. In C++, all types are what C# would consider value types, and if they're default constructible (as built-in types, POD structs and class types with default constructors are), they are initialized using value initialization (the default constructor syntax), as James McNellis showed: (and shamelessly copied here)

template <typename T>
T get()
{
    return T(); // returns a value-initialized object of type T
}

if T has a default constructor, it is invoked. If it has no constructors, everything is initialized to zero/null.

And if the type is not default constructible, there is no default value the object could be given.

like image 39
jalf Avatar answered Sep 20 '22 21:09

jalf