I was taking a course on C++ on this website called Udemy. I had just gotten finished with a video lecture on Classes. I decided to experiment around with the idea of using classes and header files, as is encouraged by the teacher. I began by creating 2 .cpp files and 1 header file. I created a function in the second .cpp file, then created a class for it in the header file, and tried calling it in the first .cpp file, but got the error in the first .cpp file: invalid use of 'Learn2::Learn2'. This is the first .cpp file:
#include "Learn1.h"
#include "Learn2.cpp"
Learn2 learn2;
int main() {
string input;
cout << "Would you like to see the menu of processes? (yes/no)" << endl;
cin >> input;
if (input == "yes"){
showMenu();
}
else{
cout << "all done here" << endl;
}
return 0;
}
void showMenu(){
cout << "Processes: " << flush;
cout << " Quit(4) Edit(5)" << endl;
int input;
cin >> input;
switch(input) {
case 4:
cout << "You selected: quit(4)" << endl;
break;
case 5:
cout << "You selected: edit(5)" << endl;
break;
default:
cout << "not recognized" << endl;
learn2.Learn2();
}
}
#include "Learn1.h"
Learn2::Learn2(){
cout << "hi" << endl;
}
* Learn1.h
*
* Created on: Nov 19, 2016
* Author: jacob
*/
#ifndef LEARN1_H_
#define LEARN1_H_
#include <iostream>
#include <limits.h>
#include <iomanip>
using namespace std;
class Learn1 {
public:
Learn1();
virtual ~Learn1();
};
void showMenu();
class Learn2 {
public:
Learn2();
};
#endif /* LEARN1_H_ */
In a class named Learn2
, all functions named Learn2
are constructors. They can be used only to construct objects, not to be called as member functions on objects of the class.
Hence,
learn2.Learn2();
is wrong.
You can use
learn2 = Learn2();
to construct a brand new object and then assign it to learn2
.
If the class had other member functions, you could call them on learn2.
class Learn2 {
public:
Learn2();
display() { std::cout << "In Learn2::display\n"; }
};
Learn learn2;
learn2.display();