Search⌘ K

- Examples

Explore how the default keyword allows compiler-generated constructors and destructors, and how delete restricts unwanted operations like copying or heap allocation. This lesson helps you master better control over class behavior in C++ for safer and clearer code.

Constructors and destructors using default #

C++
#include <iostream>
class SomeType{
public:
// state the compiler generated default constructor
SomeType() = default;
// constructor for int
SomeType(int value){
std::cout << "SomeType(int) " << std::endl;
};
// explicit Copy Constructor
explicit SomeType(const SomeType&) = default;
// virtual destructor
virtual ~SomeType() = default;
};
int main(){
std::cout << std::endl;
SomeType someType;
SomeType someType2(2);
SomeType someType3(someType2);
std::cout << std::endl;
}

Explanation #

  • In this example, we can see how default can be used to get the default implementations of constructors and destructors from the compiler.

  • Since we have defined a parameterized constructor in line 10, ...