C++Builder Learn what is Trivial Default Constructor in C++

FireWind

Свой
Регистрация
2 Дек 2005
Сообщения
1,957
Реакции
1,203
Credits
4,034
Learn what is Trivial Default Constructor in C++
By Yilmaz Yoru June 21, 2021

The Constructor in C++ is a function, a method in the class, but it is a ‘special method’ that is automatically called when an object of a class is created. We don’t need to call this function. Whenever a new object of a class is created, the Constructor allows the class to initialize member variables or allocate storage. This is why the name Constructor is given to this special method.
C++:
class myclass
{         
  public:   
    myclass()
    {
       std::cout << "myclass is constructed!\n";
    };
};
There are different contractor types and the Default Constructor in classes is one of these. This method not only used in classes but also used with struct and union data types Do you want to learn what is default constructor or what kind of methods we have that we can declare and use default constructors? In this post, we will try to explain the Default Constructor with examples.

A Default Constructor is a constructor type in Classes that is called when class is defined with no arguments, or it is defined with an empty parameter list, or with default arguments provided for every parameter. A type with a public default constructor is Default Constructible; There are different methods to use this Default Constructor and one of the terms that we meet sometimes is Trivial Default Constructor. If you are looking for how do we declare a trivial default constructor, please read below.

Trivial Default Constructor​

A Trivial Default Constructor is a constructor that does not act. All data types compatible with the C are trivially default-constructible.
C++:
class my_class
{
   // this class has trivial default constructor
};
The Default Constructor for class is Trivial if all listed conditions below are provided,
  • The constructor is not defined by the user, not defined implicitly or not defaulted on its first declaration
  • The class has no virtual member functions
  • The class has no virtual base classes
  • The class has no non-static members with default initializers.(since C++11)
and also note that,
  • Every direct base of the class has a trivial default constructor
  • Every non-static member of class type has a trivial default constructor
Here is a full example about Trivial Default Constructor,
C++:
#include <iostream>
 
class my_class
{
   // this class has trivial default constructor
};
 
class my_other_class : public my_class
{
   // this class has trivial default constructor
};
 
int main()
{
 my_other_class test; // test object has trivial default constructor
 
 getchar();
 return 0;
}