asrofil
asrofil

Reputation: 25

Simple Class and Header in Separate File Won't Work

I'm currently learning c++ for a week and here's my problem:

run.cpp

#include <iostream>
#include "Abc.h"

int main(){
    int a;
    std::cout << "Enter a : ";
    std::cin >> a;

    // Object Initialization
    Abc AbcObj();
}

the header, Abc.h :

#ifndef ABC_H
#define ABC_H


class Abc
{
    public:
        Abc();

    protected:

    private:
};

#endif // ABC_H

and finally my cpp file for implementation, Abc.cpp:

#include "Abc.h"
#include <iostream>

Abc::Abc()
{
    std::cout << std::endl << "Object created ";
}

Why don't I get output on my console? I'm expecting "object created" should be on the console. These files are in the same directory.

Upvotes: 2

Views: 88

Answers (1)

user14248283
user14248283

Reputation:

You error doesn't come up because you've used different files, so I have used one in this example

struct Foo
{
    int a;
    Foo()
    {
       std::cout << "Constructor called!";
    }
};

int main()
{
    Foo obj();
}

Why don't you see the message? You can read this thread

The problem here is, Foo obj() is taken as a function declaration. To fix this you need to remove the ()

int main()
{
    Foo obj;
} 

Constructor called!

Upvotes: 1

Related Questions