Constructor of type int
First and second are exactly same as both are initialization. Third one is different, as this is assignment. These differences are as per the C++ Standard. However, the compiler can treat all three as same!
Why does constructor choose type INT instead of SHORT when invoked with a parameter of type CHAR?
The result of integral promotion is int
(not short
) for char
; and promotions (e.g. char
-> int
) have higher ranking than other conversions (e.g. char
-> short
) in overload resolution.
prvalues of small integral types (such as
char
) may be converted to prvalues of larger integral types (such asint
).
signed char
orsigned short
can be converted toint
;unsigned char
,char8_t
(since C++20) orunsigned short
can be converted toint
if it can hold its entire value range, andunsigned int
otherwise;char
can be converted toint
orunsigned int
depending on the underlying type:signed char
orunsigned char
(see above);
and (emphasis mine)
Note that all other conversions are not promotions; for example, overload resolution chooses
char
->int
(promotion) overchar
->short
(conversion).
Do built-in types have default constructors?
A constructor is a member function (constructors are fully specified in clause 12 of the C++ Standard, which covers special member functions like constructors and destructors).
A member function can only be defined for a class type (C++03 9.3/1 says "Functions declared in the definition of a class, excluding those declared with a friend specifier, are called member functions of that class").
So non-class types (including fundamental types, array types, reference types, pointer types, and enum types) do not have constructors.
I don't have a copy of The C++ Programming Language to read the context of the quote that "Built-in types also have default constructors," but I would guess that Stroustrup is either using the term "constructor" in a loose, non-technical sense, or the meaning of the term or the way in which it is used in the Standard changed between when the book was published and when the language was standardized. I'd guess the former is far more likely than the latter.
custom constructors for built-in types in c++
Well, there is no constructor for a basic pointer - in the sense that there is no function implicitly called in order to initialise the pointer.
The closest you can come is to use a user-defined conversion operator function
class Entity
{
public:
operator int *();
};
Entity::operator int *()
{
// return something appropriate that is of type int *
}
// sample usage in a function somewhere
int *p = some_entity; // implicitly conversion that calls the operator int *()
int *another_p = static_cast<int *>(some_entity); // explicit conversion
int *yet_another_p = some_entity.operator int *();
There are variants of this, depending on what form of const
qualification is needed (e.g. if the operator function doesn't change the object it acts on, it should be const
and may be defined as operator const int *()
).
It is necessary to ensure that the pointer returned by the operator function is treated appropriately. If the user defined operator function returns a member of some_entity
, it cannot be used once some_entity
ceases to exist. Similarly, if it uses dynamic memory allocation (e.g. return the result of a new
expression) the caller must explicitly release that memory to avoid a memory leak.
Constructors with the same primitive type as parameter
It's not possible to have same name and same signature for two methods or constructors.
In your case if you call new Data(10)
to create an instance of Data
the compiler won't know which constructor to call to create the instance.
You can have a second boolean
argument to mention what kind of instance to be created.
public Data(int size, boolean isQueue)//constructor
{
if(isQueue){
len = 0;
Queue = new int[size];
front = -1;
rear = -1;
}else{
this.size = size;
this.stackArray = new int[size];
this.top = -1;
}
}
JLS: §8.4.2 Method Signature
Is ok to have one constructor for each built in data types C++
The only reason you should make more than one constructor is if extra handling or conversion logic is required. For example:
#include <string>
#include <iostream>
class myClass
{
public:
unsigned long long int words;// public for ease of example
// will consume anything convertable to unsigned long long
myClass(unsigned long long int val) :
words(val)
{
}
// will consume anything convertable to std::string, and then convert
// the string to unsigned long long
myClass(std::string val) :
words(std::stoull(val))
{
}
};
int main()
{
std::cout << myClass{ 10 }.words << ": 10" << std::endl;
std::cout << myClass{ -10 }.words << ": -10 (Two's compliment wrap)" << std::endl;
std::cout << myClass{ 3.14 }.words << ": 3.14 (Truncated)" << std::endl;
std::cout << myClass{ "10" }.words << ": \"10\"" << std::endl;
std::cout << myClass{ "-10" }.words << ": \"-10\" (Two's compliment wrap)" << std::endl;
}
10 is converted easily. -10 and 3.14 are converted, but will generate warnings because the value will be damaged by the translation. "10" and "-10" will be accepted by the string
-parametered constructor, but "-10" will be mangled by std::stoull
. Additional logic, and probably use of strtoull
, will be required to handle this, if required.
What is this weird colon-member ( : ) syntax in the constructor?
It's a member initialization list. You should find information about it in any good C++ book.
You should, in most cases, initialize all member objects in the member initialization list (however, do note the exceptions listed at the end of the FAQ entry).
The takeaway point from the FAQ entry is that,
All other things being equal, your code will run faster if you use initialization lists rather than assignment.
Does C++ constructor return an object?
Indeed a constructor doesn't have a return value.
But Number(10)
is an object of type Number
. And that is an expression with a value.
Related Topics
Where Should Non-Member Operator Overloads Be Placed
What Happens When a Function That Returns an Object Ends Without a Return Statement
Date/Time Conversion: String Representation to Time_T
Deleted Function in Std::Pair When Using a Unique_Ptr Inside a Map
In C++ 11, How to Invoke an Arbitrary Callable Object
Why Can't I Replace Std::Map with Std::Unordered_Map
Gcc Can Compile a Variadic Template While Clang Cannot
Memory Allocation and Deallocation Across Dll Boundaries
C++ Double Dispatch for Equals()
Convert Integer to Binary and Store It in an Integer Array of Specified Size:C++
Unique_Ptr and Openssl's Stack_Of(X509)*
Using << Operator to Write to Both a File and Cout
The Most Efficient Way to Reverse a Number
Calculating the Info-Hash of a Torrent File
Reading JSON File with C++ and Boost
How to Write a Large Number in C++ Source Code with Spaces to Make It More Readable