Home > Backend Development > C++ > Why Doesn't My Class Constructor Get Called?

Why Doesn't My Class Constructor Get Called?

Barbara Streisand
Release: 2024-12-26 14:57:14
Original
956 people have browsed it

Why Doesn't My Class Constructor Get Called?

Why is there no call to the constructor?

The provided code seeks to create an instance of the Class class; however, its current implementation results in unexpected behavior. The code defines a constructor, which should be executed upon object creation, but the output does not reflect this.

Upon closer examination, the code contains a crucial error. The line Class object(); is not correctly declaring an object of the Class class. Instead, it is mistakenly declaring a function with the same name as the class.

To rectify this issue, the code should be modified to correctly create an instance of the Class class:

#include<iostream>
using namespace std;

class Class
{
public:
    Class()
    {
        cout << "default constructor called" << endl;
    }

    ~Class()
    {
        cout << "destructor called" << endl;
    }
};

int main()
{
    Class object; // Corrected line: Create an object of Class
}
Copy after login

With this correction, the expected output will be produced, as the default constructor is now properly called upon object creation.

The above is the detailed content of Why Doesn't My Class Constructor Get Called?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template