I tried two methods for class creation.
1) Create class in same file as main.cpp and define the class's members functions in same file as main.
2) Create class in a separate (.h) file and define the class's member functions in a separate (.cpp) source file. When I do 1) everything works as predicted. When I do 2) I cannot use the class without passing in an initial value to the constructor, (default constructor) arguments seem to not initialize the code or something. I am really confused why it doesn't work in 2) but it works in 1) when they should be doing the exact same thing.
1) main.cpp
#include <iostream>
using namespace std;
class Dog {
public:
Dog();
~Dog();
int years_old;
};
Dog::Dog() {
years_old = 10;
std::cout << "we are inside dog constructor" << std::endl;
}
Dog::~Dog() {}
int main() {
Dog dogg;
cout << "Dog is: " << dogg.years_old << "years old!" << endl;
cout << "We are in main" << endl;
return 0;
}
2) Dog.h:
#ifndef DOG_H
#define DOG_H
class Dog {
public:
Dog(); // if I pass in arguments both here and in main and in Dog.cpp this works
~Dog();
int years_old;
};
#endif
2) Dog.cpp
#include <iostream>
#include "Dog.h"
Dog::Dog() {
years_old = 10;
std::cout << "we are inside dog constructor" << std::endl;
};
Dog::~Dog() {
};
2) main.cpp
#include <iostream>
#include "Dog.h"
using namespace std;
int main() {
Dog dogg;
cout << "Dog is: " << dogg.years_old << "years old!" << endl;
cout << "We are in main" << endl;
return 0;
}
I get this error:
Undefined symbols for architecture x86_64:
"Dog::Dog()", referenced from:
_main in main-ddbb4d.o
"Dog::~Dog()", referenced from:
_main in main-ddbb4d.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)