Turbosheep
Turbosheep

Reputation: 183

Class constructor not working?

Code:

In class header file:

 class Coconuts
{
public:
    Coconuts constructor();

};

In class .cpp file:

     #include "Coconuts.h"
     #include <iostream>
     #include <string>
     using namespace std;


Coconuts::constructor()
{
    cout << "\nYay coconuts are initialized";
};

In main():

 Coconuts Object1;

My program runs without any erros whatsoever, but the constructor isn't initialized and the message is not displayed. Suggestions, anyone?

Upvotes: 3

Views: 1559

Answers (2)

jcoder
jcoder

Reputation: 30055

That's not a constructor, the constuctor is just the name of the class :-

 class Coconuts 
 { 
 public:     
    Coconuts();  
 };

and

Coconuts::Coconuts()  
{      
    cout << "\nYay coconuts are initialized";  
};

Upvotes: 2

Nicol Bolas
Nicol Bolas

Reputation: 474286

Constructors are not functions named constructor. The "name" of a constructor is the name of the class itself. Note that constructors are not normal functions and cannot be directly referenced by name, which is why I put "name" in quotation marks.

Your code should be as follows:

//.h
class Coconuts
{
public:
    Coconuts();
};

//.cpp
Coconuts::Coconuts()
{
    cout << "\nYay coconuts are initialized";
};

Upvotes: 9

Related Questions