It refers to automatic deduction of the data type of expression in a programming language.
As all the types are deduced in the compiler phase only, the time for compilation increases slightly but it does not affect the run time of the program.
auto
The auto keyword specifies that the type of the variable that is being declared will be automatically deducted from its initializer.
In the case of functions, if their return type is auto then that will be evaluated by return type expression at runtime.
Good use of auto is to avoid long initializations when creating iterators for containers.
int& fun() {}; // Function that returns a ‘reference to int’ type
void main()
{
auto m = fun(); // m will default to int type instead of int& type
auto& n = fun(); // n will be of int& type because of & with auto
}
decltype
auto lets you declare a variable with a particular type whereas decltype lets you extract the type from the variable.
int main()
{
int x = 5;
// j will be of type int : data type of x
decltype(x) j = x + 5;
cout << typeid(j).name(); // i
}
final
It restricts inheritance.
We cannot derive from a base class which is declared final.
class Base final
{
};
class Derived : public Base // This will generate error
{
};
It is also used to restrict function overriding.
class Base
{
virtual void show() final // Function needs to be virtual to become final
{
}
};
class Derived : public Base
{
void show() // This will generate error
{
}
};
final functions of base class cannot be overridden in derived class.
Delegation of Constructors
class Test
{
int x = 10; // In class initialization
int y = 20; // In class initialization
public:
Test(int a, int b)
{
x = a;
y = b;
}
Test() : Test(1, 1) // Delegation of constructor
{
}
};
In-class initializer: We can initialize the data members inside the class itself.
Delegation of Constructors: One constructor can call another constructor within the same class.
Ellipsis
They are Used for defining variable argument functions.
… is used as symbol of ellipsis.
printf and scanf of C language are example of ellipsis.
#include <iostream>
#include <cstdarg> // This header file is required
using namespace std;
int sum(int n, ...)
{
va_list list;
va_start(list, n);
int x;
int s = 0;
for (int i = 0; i < n; i++)
{
x = va_arg(list, int);
s += x;
}
return s;
}
int main()
{
cout << sum(3, 10, 20, 30);
cout << sum(5, 1, 2, 3, 4, 5);
}