0

Original

As a basic test, I can define a class in my Main.cpp and get the expected behavior from the constructor

#include <iostream>

class PrintConstructor
{
public:
   PrintConstructor() {
      std::cout << "Hello World!";
   }
};

int main() {

    PrintConstructor myResult;

    return 0;
}

When compiling $ g++ -o Main Main.cpp I get the printed "Hello World!" result.

However when placing my class into a separate .cpp and .h files I'm not getting anything printed.

Modularized

PrintConstructor.cpp

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

class PrintConstructor()
{
public:
   PrintConstructor() {
      std::cout << "Hello World!";
   }
};

PrintConstructor.h

If I leave this blank, I don't get any errors, but I don't have the constructor printing like I'm expecting.

I have tried

class PrintConstructor
{
public:
   PrintConstructor();
};

but I get an `undefined reference to PrintConstructor::PrintConstructor()'

When blank, I don't get an error, but I don't have the behavior from the constructor I'm expecting.

class PrintConstructor
{

};

Main

#include <iostream>
#include "LinkedList.h"
int main() {

    PrintConstructor myResult;

    return 0;
}
Hofbr
  • 868
  • 9
  • 31
  • 4
    You have defined your class twice. This is ODR violation and so undefined behavior, no diagnostic required. See dupe: [Multiple Definition of Class in Different Translation unit](https://stackoverflow.com/questions/36607185/multiple-definition-of-class-in-different-translation-unit). The solution is [Separating class code into a header and cpp file](https://stackoverflow.com/questions/9579930/separating-class-code-into-a-header-and-cpp-file) – Jason Oct 16 '22 at 05:34
  • 2
    In `PrintConstructor.cpp` just implement the constructor, don't define the whole class. `PrintConstructor::PrintConstructor() { std::cout << "Hello World!"; }` – Ted Lyngmo Oct 16 '22 at 05:36
  • 3
    Also, see [Separating class code into a header and cpp file](https://stackoverflow.com/questions/9579930/separating-class-code-into-a-header-and-cpp-file) for solution. These things are explained in any [good c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). These books are also available as PDFs for free. – Jason Oct 16 '22 at 05:38
  • 2
    `class PrintConstructor()` in the first example is already wrong and it shouldn't compile. The parentheses do not make sense there for any syntax construct. If you remove them you have a class definition and a second one in the header file. There should be only the one in the header file. Out-of-class definition of a constructor uses a different syntax, see duplicates. – user17732522 Oct 16 '22 at 08:03

0 Answers0