I want to include class, but it doesn't work - c++

I'm just learning C++. I'm following a YouTube video, but I'm stuck at this stage. Below is my files.
// main.cpp
#include <iostream>
#include "Person.h"
int main()
{
Person foo;
foo.set_age(25);
std::cout << foo.get_age() << std::endl;
return 0;
}
// Person.h
#ifndef PERSON_H
#define PERSON_H
#pragma once
class Person
{
public:
void set_age(int a);
int get_age();
private:
int age;
};
#endif
// Person.cpp
#include "Person.h"
void Person::set_age(int a)
{
age = a;
}
int Person::get_age()
{
return age;
}
I just set up the development environment in vscode and installed code runner.
Whenever I click the Run button here
It says
launch: program '.....main.exe' does not exist
Is there a tool like php composer that automatically manages it?
Moved the contents of the .cpp file to the .h file.
It worked fine. But I would like to separate the two files for management.

Related

Several strange errors when building project using separate files C++

I'm able to build and run a particular project in Visual Studio when all of the code is in one main .cpp file, but when I separate the file into a class (.cpp and .h) and main .cpp file, I get several weird errors.
Here is the code when it's in 3 separate files, and not working:
//main.cpp
#include "student.h"
#include <string>
#include <iostream>
using namespace std;
int main()
{
std::cout << "Hello World!\n";
Student student;
student.setStudentID("A1C");
student.print();
}
//Student.h
#ifndef STUDENT_H
#define STUDENT_H
class Student
{
public:
Student();
string getStudentID() const;
void setStudentID(string studentID);
void print();
private:
string studentID;
};
#endif
//Student.cpp
#include "Student.h"
#include <string>
#include <iostream>
using namespace std;
Student::Student() {
this->studentID = "default";
}
string Student::getStudentID() const {
return this->studentID;
}
void Student::setStudentID(string studentID) {
this->studentID = studentID;
}
void Student::print() {
cout << "student ID: " << studentID << endl;
}
Here is the code when it's all in one main.cpp file, and working:
#include <string>
#include <iostream>
using namespace std;
class Student
{
public:
Student();
string getStudentID(); //const?
void setStudentID(string studentID);
void print();
private:
string studentID;
};
int main()
{
std::cout << "Hello World!\n";
Student student;
student.setStudentID("A1C");
student.print();
}
Student::Student() {
this->studentID = "default";
}
string Student::getStudentID() { //const?
return this->studentID;
}
void Student::setStudentID(string studentID) {
this->studentID = studentID;
}
void Student::print() {
cout << "student ID: " << studentID << endl;
}
Here are some of the errors that I get:
In the file Student.h you are using string, but string is not (yet) known. Read the Include file from top to bottom. Nowhere in the file is there any hint as to what string is supposed to be.
#include <string> in your Student.h file will introduce std::string to the file. From here on, std::string will be valid. But that's still not enough, since you are using string and not std::string in your class.
Do not include a using namespace std in your header file. If you do so, you force this namespace on all your "customers" of the header file. If any other file includes your Student.h with the using namespace in it, they will also get the using namespace... statement, even if they do not want it. Headerfiles should be self contained and should not introduce stuff, others may not want.
Also do not add a using std::string in your header file. While not as bad as a using namespace std there may be (and later in your professional life will be) instances, where you have different kinds of string. Perhaps a std::string and an oldfashioned::string or utf_something::string.
For simplicity, just write std::string studentId. IOW, use the fully qualified name of string in your header file.
In .cpp files these rules are somewhat relaxed, since no other file will include your .cpp file.
Bonus:
lookup #pragma once
always include system headers before your own headers
But beware of include order. Every header file should include all headers it needs, because ...
... the worst thing that can happen is that your code changes depending on the order in which you include headers. It should not matter. Including "Student.h" should introduce the Student class and nothing else.
Bonus++
take your time to learn about the C(++) preprocessor. #include is not really a C++ language statement like class, for etc... It is just a directive for the compiler to read the included file first.
Your compiler will have a switch (such as /P with Microsoft Visual C++) which will not compile the code but produce the actual included files and store the in a *.p (or something) file. It will let you see what the preprocessor does with your code before it is passed on to the compiler. It's an interesting and teaching experience. Try it. Don't be put off by the seemingly complex file. Search for "class Student" in that file and take it from there.
change student.h to this
//Student.h
#ifndef STUDENT_H
#define STUDENT_H
#include <string>
class Student
{
public:
Student();
std::string getStudentID() const;
void setStudentID(std::string studentID);
void print();
private:
std::string studentID;
};
#endif
and it compiles and runs fine
BTW.
dont do this
void Student::setStudentID(string studentID) {
this->studentID = studentID;
}
have a naming convention for fields in a class so they are distinct
ie
//Student.h
#ifndef STUDENT_H
#define STUDENT_H
#include <string>
class Student
{
public:
Student();
std::string getStudentID() const;
void setStudentID(std::string studentID);
void print();
private:
std::string studentID_; <<<<========
};
then
void Student::setStudentID(string studentID) {
studentID_ = studentID;
}
why, because
First its the accepted way in c++ world (the naming standard might differ, m_ prefix is common too)
second you might write this
void Student::setStudentID(string studentID) {
studentID = studentID;
}
which will compile but is maybe not what you mean. Of course here its obvious but in denser code, not so much

In function int main(): class name was not declared in this scope

Im using vscode and im new to c++. I learned how to create a header file link to its cpp and use it to main.cpp. The only problem bugs me out is why it causes an error this is my simple code.
Name.h
#include <iostream>
#include <string>
class myname
{
public:
void setname(std::string name);
void prname();
private:
std::string Name;
};
Name.cpp
#include "Name.h"
void myname::setname(std::string name)
{
Name = name;
}
void myname::prname()
{
std::cout<<"Hello :"<<Name<<std::endl;
}
Maiin.cpp
#include <iostream>
#include <string>
#include "Name.h"
using std::cout;
using std::string;
using std::endl;
int main()
{
myname Epoy; // IN FUNCTION INT MAIN: ERROR myname was not declared in this scope
Epoy.setname("Jomar"); //note myname <-rename "BUT THIS IS NOT THE ERROR CAUSE THIS JUST HAPPEN BECAUSE OF THE ERROR ABOVE "
Epoy.prname();
return 0;
}
also i tried so many method i even compiled this by using g++ Maiin.cpp Name.cpp - o Maiin
Still didnt work
Edit: Community want me to add more details.
What I asked was, have you write header guards in your header file: #ifndef Name_H, #define Name_H, #endif ? Since you use vscode you have to done it manually.
Like this:
#ifndef Name_H
#define Name_H
#include <iostream>
#include <string>
class myname
{
public:
void setname(std::string name);
void prname();
private:
std::string Name;
};
#endif
you missing a C++ constructor:
class Foo {
public:
Foo() { /* your init code */ } // <-- this is a std. C++ constructor
~Foo() { /* your clean-up code */ } // <-- this is a std. C++ de-structor
};
int main(int argc, char **argv) {
Foo bar; // here, you don't need the: ( ) object on heap !
}

Getting class type redefinition and a few other errors

I'm creating a student data management console application for a project. I created a class called Student which is storing all the data that a student needs to have, and it also has all the getters and setters associated with it. Here is how all my files are laid out:
Student.h
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
string name;
string id;
string email;
int presentation;
int essay1;
int essay2;
int project;
public:
//constructor
//Student();
//setters
void set_name(string);
void set_id(string);
void set_email(string);
void set_presentation(int);
void set_essay1(int);
void set_essay2(int);
void set_project(int);
//getters
string get_name();
string get_id();
string get_email();
int get_presentation();
int get_essay1();
int get_essay2();
int get_project();
};
Student.cpp
#include <iostream>
#include <string>
#include "Student.h"
using namespace std;
//constructor definition
/*
Student::Student(void) {
cout << "Student created" << endl;
}
*/
//setter definition
void Student::set_name(string s) {
name = s;
}
void Student::set_id(string s) {
id = s;
}
void Student::set_email(string s) {
email = s;
}
void Student::set_presentation(int a) {
presentation = a;
}
void Student::set_essay1(int a) {
essay1 = a;
}
void Student::set_essay2(int a) {
essay2 = a;
}
void Student::set_project(int a) {
project = a;
}
//getter definition
string Student::get_name() {
return name;
}
string Student::get_id() {
return id;
}
string Student::get_email() {
return email;
}
int Student::get_presentation() {
return presentation;
}
int Student::get_essay1() {
return essay1;
}
int Student::get_essay2() {
return essay2;
}
int Student::get_project() {
return project;
}
Main.cpp
#include <iostream>
#include <string>
#include "Student.h"
using namespace std;
int main() {
cout << "Hello World!" << endl;
Student student1;
Student student2;
Student student3;
student1.set_name("John");
student2.set_name("Bob");
student3.set_name("Carl");
return 0;
}
When I try to run my program, I get, amongst others, the following errors:
Error 1 error C2011: 'Student' : 'class' type redefinition
Error 2 error C2079: 'student1' uses undefined class 'Student'
Error 5 error C2228: left of '.set_name' must have class/struct/union
Error 9 error C2027: use of undefined type 'Student'
How can I go about fixing this issue?
I'm quite sure this is an error caused by the fact that student.h is included twice in a certain .cpp file. Thus you need to use so-called header guards to make sure the file is only included once in every .cpp file:
#ifndef STUDENT_H
#define STUDENT_H
#include <iostream>
#include <string>
using namespace std;
class Student {
/* ... */
};
#endif
The idea behind this is that an #include is a preprocessor directive that results in the argument file being copied into the file where the #include was issued. Hence, if files A and B include Student.h, and file C includes both files A and B, then the declaration of class Student is going to end up duplicated. Hence the error. The above macros make sure that this doesn't happen.
Edit as per the question author's comment:
#pragma once is the same as #ifndef .. #define #endif but non-standard .
See #pragma once vs include guards? for reference.
I had the same error. I just clean and rebuild the solution and error resolved.

C++ class in separate file not compiling. Already defined in Class.obj one or more multiply defined symbols found

So I've done extensive googling and searching on StackOverflow and am unable to find a solution despite several answers with this exact issue.
I am trying to create a test class in an external file called Fpc5.cpp
It's contents are:
Fpc5.cpp
#include "stdafx.h"
#include "Fpc5.h";
#include <iostream>
using std::cout;
class Fpc5 {
int bar;
public:
void testMethod();
};
void Fpc5::testMethod() {
cout << "Hey it worked! ";
}
and my main .cpp file:
Test.cpp
// Test.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "iostream"
//#include "Fpc5.cpp"
#include "Fpc5.h";
using std::cout;
using std::cin;
using std::endl;
int main()
{
cout << "Hello" << endl;
Fpc5 testObj;
testObj.testMethod();
system("pause");
return 0;
}
all the answers I've read indicate this is caused becaused I used to be including the class in the main file itself which is why I created a header file
Fpc5.h
#pragma once
void testMethod();
This changed the error, but still did not fix the issue. Currently my Test.cpp does not recognize a Fpc5 class. I've also tried adding the Fpc5.cpp and Fpc5.h in stdafx.h and that still does not resolve the issue.
stdafx.h
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
// TODO: reference additional headers your program requires here
//#include "Fpc5.cpp"
#include "Fpc5.h"
I'm sure this a simple syntax/conceptual understanding error, but I'm quite new to c++ and am not sure what is wrong.
This is definition of your class and it must be in Fpc5.h
class Fpc5 {
int bar;
public:
void testMethod();
};
Then, you have Fpc5.cpp where you implement methods of the class:
#include "Fpc5.h" // Compiler needs class definition to compile this file!
void Fpc5::testMethod()
{
}
And then you can use Fpc5 class in Test.cpp
#include "Fpc5.h"
int main()
{
Fpc5 foo;
foo.testMethod();
return 0;
}
As an alternative you can pack everything into Test.cpp
Move the definition of your class:
class Fpc5 {
int bar;
public:
void testMethod();
};
to the header file, "Fpc5.h".
Implement the methods to "Fpc5.cpp".

'Undefined reference to Class::method()'

Recently I've been learning how to create methods within classes so that I only have to write a method once and for each of that class I instantiate I can call the one method and it will work only on the variables of the object that called it, I know how to do this when only using main.cpp and no headers however I am confused on how I should be writing this when I use a class header and cpp.
I have a sample of code similar to what I want to achieve:
#include <iostream>
using namespace::std;
class Object
{
public:
int stuff;
void manageStuff();
Object();
};
void Object::manageStuff()
{
stuff++;
}
Object::Object() : stuff(0) {}
Object object1, object2;
int main() {
for (int i = 0; i < 10; i++)
{
object1.manageStuff();
object2.manageStuff();
cout << object1.stuff << "\n";
cout << object2.stuff << "\n";
}
}
This works fine and allows me to have two instances of Object and a method that works independently for each instance, this is my current project:
main.cpp:
#include <iostream>
#include "Test.h"
using namespace std;
int main()
{
Test test;
for (int i = 0; i < 10; i++)
{
test.count(); // Here's my error "undefined reference to Test::count"
}
return 0;
}
Test.cpp
#include <iostream>
#include "Test.h"
using namespace std;
Test::Test()
{
//ctor
}
Test::~Test()
{
//dtor
}
Test.h
#include <iostream>
#ifndef TEST_H
#define TEST_H
class Test
{
public:
Test();
virtual ~Test();
void count();
int counter();
};
#endif // TEST_H
and finally TestFunctions.h
#include <iostream>
#include "Test.h"
#ifndef TESTFUNCTIONS_H_INCLUDED
#define TESTFUNCTIONS_H_INCLUDED
void Test::count()
{
Test::counter++;
std::cout << Test::counter;
}
#endif // TESTFUNCTIONS_H_INCLUDED
I'm sure that there will be something that's very obviously wrong to a more seasoned programmer and I'm about to look a bit thick but any help would be greatly appreciated
Thanks!
I would suggest getting rid of TestFunctions.h, and adding the implementation of Test::count() to Test.cpp. Currently, the TestFunctions.h header is not included anywhere, so you have no access to the definition from main.
You defined (i.e. implemented) Test::count() in a header file (TestFunctions.h), but you never included it anywhere so the code there is not compiled.
You should change it to be in a .cpp file, compile it and link it with the other source files. There's no reason why not to place it in Test.cpp.
Rename TestFunctions.h into TestFunctions.cpp, make it compiled same way as main.cpp and linked.
Alternatively, include TestFunctions.h somewhere, e.g. main.cpp