Using header and .cpp file for Classes - don't completely understand | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Using header and .cpp file for Classes - don't completely understand

Hi, First off, very new to programming here so any clarification / assistance would be great. I am not taking any college course and just doing this on my own for my own knowledge. I have been going through the examples/tutorial and I am trying to code my own example around the exercise for Class Birthday. I am trying to use the separate file approach here but getting multiple different errors and would like some advice on where I am going wrong here. Here is my .h file code: #ifndef MYCLASS_H #define MYCLASS_H class MyBirthday { public: MyBirthday() { } void printDate(); protected: private: }; #endif // MYCLASS_H Here is my .cpp code: #include <iostream> #include "MyClass.h" using namespace std; MyBirthday::MyBirthday(int d, int m, int y) :date (d), month (m), year (y) { //ctor } void MyBirthday::printDate() { cout <<month<<"/"<<day<<"/"<<year<<endl; } int date, month, year; Main .cpp code #include <iostream> #include <cstdlib> #include "MyClass.h" using namespace std; int main() { //working with Classes in header files MyBirthday obj(); obj.printDate(04,29,1973); return 0; } I am just initially trying to output a birthdate. Once I get this I will change it up for user entry but just getting lots of errors like: error: request for member 'printDate' in 'obj', which is of non-class type "MyBirthday" Any suggestions would be great - thanks!

12th Sep 2017, 8:02 PM
scott carlson
scott carlson - avatar
2 Answers
+ 2
you need to put the parameters from the constructor in cpp and paste them into the constructor parameter of the header file and also remove the curley brackets from the constructor in the header so its like a function. you also set values in the constructor for variables that dont exist and you need to input the birthday values in the brackets when making the object as thats what the constructor uses. (idk which file the int date,month,year declaration is but it seems you want it in the header file in the class)
12th Sep 2017, 8:21 PM
Enzo
Enzo - avatar
+ 1
Enzo - thanks for your help! I was able to move things around and retry a few times and got it to work. Makes sense now that it's correct - thanks again
13th Sep 2017, 1:25 AM
scott carlson
scott carlson - avatar