I have a basic question since I havent used C++ in a while.
I have a header file like so:
It will remain the same, however the cpp file will change
#ifndef DOG_H_
#define DOG_H_
class Dog : Animal {
private:
std::string breed;
public:
Dog(std::string name, int age, std::string);
};
#endif /* DOG_H_ */
and then CPP version 1:
#include "Dog.h"
Dog::Dog(std::string name, int age, std::string breedIn){
Animal(name, age);
breed = breedIn;
}
or CPP Version 2:
#include "Dog.h"
class Dog{
Dog::Dog(std::string name, int age, std::string breedIn){
Animal(name, age);
breed = breedIn; // the var name breed does not resolve
}
};
The difference between version 1 and version 2 is that the 2nd one is wrapped in the class definition.
Why should I do one and not the other.
Secondly, in the second version, the variable name breed does not resolve. Why is that?
Q: in the second version, the variable name breed does not resolve. Why is that?
A: Because it's wrong.
You declare your class once, e.g. in the header.
You may define your method implementations either in-line (in the header itself, when you declare the class), or in a separate .cpp (as you did in example 1).
Thess links might help explain further:
http://www.cplusplus.com/doc/tutorial/classes/
http://www.cprogramming.com/declare_vs_define.html
Related
I need help with figuring out how to code the given specifications since I'm really lost in how to use the three different source files and what needs to go in all of them.
#include <iostream>
#include<string>
using namespace std;
class Person
{
public:
Person();
string getName();
int getAge();
void setName(string newName);
void setAge(int newAge);
void display();
private:
string name;
int age;
};
This is all I have for Person.h so far.
Specification
1. Given Person.h
1(a). Add a parametrized constructor that uses an initializer list for name and validates ago > 0
1(b). Create a Person.cpp that implements the functionality of Person.h
Create PersonTest.cpp that demonstrates the features of class Person
What do you mean by three different source files? If you mean Person.h, Person.cpp, and PersonTest.cpp, see below
a .h file (you should actually be using a .hpp file for c++ but it still technically works) is whats called a header file. This is where you would pretty much just name the class and all its attributes/methods, its the bare bones of the class that shows what the class is capable of doing without actually showing how its all done.
Person.cpp would be the file where you implement everything from the .h class. the top of your .h file should have something like this at the top:
#include "Person.cpp"
This tells the .h file where to look for the implementation of the methods you previously declared. To implement a method, all you need to do is something like inside of the cpp file `
void Person::setAge(int newAge) {
---implementation---
}
the "Person::" just shows that you are doing something inside of the Person class.
The third file is probably where your int main() is going to be, and make sure that at the top, it also has the #include for the header. Here is where you do what you want to test if your class is actually working, like checking that your outputs match what you expect, etc etc.
I hope this clarified a little of what you needed!
Given you know what a constructor is, you should add to this file another constuctor :
Person(string name,int age);
in the file Person.cpp you develop all the functions defined in Person.h
The file PersonTest.cpp should have a main function that calls instances of Person and prove your class works
Thanks for taking the time to view my question. I've spent a lot of time looking but can't find a solution to this problem:
I have a class Person with its' respective Header file Person.h. The cpp class is having a hard time understanding what the variables name, age, and iq are.
//Person.cpp
/*
Makes a person.
A person has a name, an age, and an IQ level.
We will create many of these objects within other classes.
*/
#include "Person.h"
Person::Person() //Empty constructor
{
}
Person::Person(string thename, int theage, int theiq)
{
name = thename;
age = theage;
iq = theiq;
}
string getName()
{
return name; //Error: identifier "name" is undefined
}
int getAge()
{
return age; //Error: identifier "age" is undefined
}
int getIq()
{
return iq; //Error: identifier "iq" is undefined
}
void setName(string aName)
{
name = aName; //Error: identifier "name" is undefined
}
void setAge(int aAge)
{
age = aAge; //Error: identifier "age" is undefined
}
void setIq(int aIq)
{
iq = aIq; //Error: identifier "iq" is undefined
}
The Header File
//=================================
// include guard
#ifndef __PERSON_H_INCLUDED__
#define __PERSON_H_INCLUDED__
//=================================
// forward declared dependencies
//=================================
// included dependencies
#include <string> //For the name
//=================================
using namespace std;
class Person
{
public:
Person(); //Default constructor
Person(string thename, int theage, int theiq); //Constructor
string getName();
int getAge();
int getIq();
void setName(int aName);
void setAge(int aAge);
void setIq(int aIq);
private:
string name;
int age, iq;
};
#endif //__PERSON_H_
SURELY I don't have to define the variables inside Person.cpp right? It already knows exactly what variables name, age, and iq are because it saw the header file already. Why can it not understand what those variables are?
If I do, or if there is anything I'm missing, make sure to really spell it out for me. I'm barely an intermediate C++ programmer so I may not understand jargon. Even things like scope, inheritance, and definitions go way over my head.
Thank you for your time.
To which ever part you're getting errors do this:
return type Person::function name(parameters)
For the declaration part of the functions.
For example for the getAge function do this:
int Person::getAge() {
return age;
}
The reason you got errors is because of the following:
First your intention was to define the functions you declared in the Person class.
In the return statement you wanted to return age member of the Person class. But you simply returned age.
The search for age begins inside the function body first. If its not found it is searched in the outer scope. If its still not found age is an unknown identifier.
After you fix it what happens is this:
The Person:: part in the return type Person::function name(parameters) means that look in the scope of the Person class.
Then in the return statement we return age member of the Person class. But this time we're looking inside the scope of the Person class, hence we return the age member and the error is fixed.
You need to change
string getName()
to
string Person::getName()
in the .cpp file. Ditto for the others., The compiler needs to know that this is a part of the class Person.
Your function
string getName()
{
return name; //Error: identifier "name" is undefined
}
is not defining the class member function. Instead you are declaring and defining a (completely different and unrelated) free function. As such, name is undefined within the scope of this function.
I'm currently trying to make a game in C++. In my code I'm trying to nest my variables so that my main doesn't have a lot of includes. My problem right now though is that the value of my variables in my class aren't changing. Stepping through the code it shows it setting the value, but it doesn't work. Anyone know what's going on? Thank you in advance.
This is what I have so far:
Location.h
#ifndef LOCATION_H
#define LOCATION_H
#include <string>
class Location
{
public:
Location(void);
Location(std::string name);
~Location(void);
std::string GetName();
void SetName(std::string value);
private:
std::string m_Name
};
#endif
Location.cpp
#include "Location.h"
Location::Location(void): m_Name("") {}
Location::Location(std::string name): m_Name(name) {}
Location::~Location(void)
{
}
std::string Location::GetName()
{return m_Name;}
void Location::SetName(std::string value){m_Name = value;}
PlayerStats.h
#ifndef PLAYERSTATS_H
#define PLAYERSTATS_H
#include "Location.h"
class PlayerStats
{
public:
PlayerStats(void);
~PlayerStats(void);
Location GetLocation();
void SetLocation(Location location);
private:
Location m_Location;
};
#endif
PlayerStats.cpp
#include "PlayerStats.h"
PlayerStats::PlayerStats(void): m_Location(Location()) {}
PlayerStats::~PlayerStats(void)
{
}
Location PlayerStats::GetLocation(){return m_Location;}
void PlayerStats::SetLocation(Location location){m_Location = location;}
main.cpp
#include <iostream>
#include "PlayerStats.h"
using namespace std;
PlayerStats playerStats = PlayerStats();
int main()
{
playerStats.GetLocation().SetName("Test");
cout<< playerStats.GetLocation().GetName()<<endl;
return 0;
}
Your immediate issue is that
Location GetLocation();
returns a copy of the location, so when you call SetName here:
playerStats.GetLocation().SetName("Test");
You're changing the name of the temporary copy, and the change is lost as soon as the semicolon is hit.
More broadly, this kind of design (nesting classes and nesting includes so that main doesn't have a lot of includes, and using a.b.c() style code to access nested members) isn't great C++ style:
Having a bunch of source files that (transitively) include a bunch of header files means that changing a single header file will trigger recompilations of a bunch of source files. Compile times can be a significant issue in larger C++ projects, so reducing compile times by controlling #include's is important. Read up on "forward declarations" for more information.
Writing code like a.b.c() is considered bad object-oriented design, because it reduces encapsulation: not only does the caller have to know about a's details, it has to know about b's also. Sometimes this is the most expedient way to write code, but it's not something to be blindly done just to reduce #include's. Read up on "Law of Demeter" for more information.
If you want to set the result of playerStats.GetLocation(), you could make GetLocation() pass-by-reference (use ampersand, &, on the return argument). Otherwise you are just setting values in a temporary copy of PlayerStats::m_Location.
Alternatively, you could use the SetLocation() function.
Helo stack people, I need your help in work I make. So I have to .h files first one is Course and the second is Student and I try to create function call getCourses but Unfortunately It's not going so well.My realization "Course ** courses" do not pass compiling and I do not know why not. I would appraise if you can help me to Understand my mistake and help me to fix them thanks.
getCourse - return list of courses
my Course .h file
#ifndef _CORSE_H
#define _CORSE_H
#include <iostream>
#include "Student.h"
class Course
{
public:
void init(std::string getName, int test1, int test2, int exam);
std::string getName();
int* getGrades();
double getFinalGrade();
private:
std::string _name;
int _exam;
int _test1;
int _test2;
};
#endif
My Student .h file-
#ifndef _STUDENT_H
#define _STUDENT_H
#include <iostream>
#include "Course.h"
class Student
{
public:
void init(std::string name, Course** courses, int crsCount);
std::string getName();
void setName(std::string name);
double getAvg();
int getCrsCount();
Course** getCourses();
private:
std::string _name;
Course** courses;
int _crsCount;
};
#endif
My get course function -
Course** student::getCourses()
{
return(this->courses);
}
The problem in the "Course** getCourses();"initialization and this applies also to the init function and Course** getCourses(); function.
error C4430: missing type specifier - int assumed. Note:C++ doe not support default-int
You have a circular dependency - each header tries to include the other, and you end up with one class defined before the other. This gives errors, because you have to declare a type before you can use its name.
Course doesn't depend on Student at all, so just remove the #include from that file.
The definition of Student only uses pointers to Course so it doesn't need the full definition. It only needs to know that the class exists, so you can replace the #include with a declaration:
class Course;
A couple more points:
both headers should include <string> since they use std::string; but not <iostream> since they don't use any I/O streams;
names beginning with an underscore and a capital, like _CORSE_H, are reserved. You should remove the underscores.
you've mis-capitalised Student in the final code snippet.
Besides what Mike Seymour wrote your course function uses lowercase student in
Course** student::getCourses()
Whereas you declared the class with a capital S. Case does matter.
I am writing an application based on wxWidgets library. I had some classes which support application data. They use types as std::string, which shouldn't be used in application written with wxWidgets lib.
E.g.
class SomeClass
{
private:
char name[80];
(.....)
public:
(.....)
};
Now I have something like that:
class SomeClass
{
private:
wxString name;
(.....)
public:
(.....)
};
(Yes, I know that char isn't string - I decided to change char to string).
Compiler throws error:
'wxString' does not name a type
I tried to include file with class in many places, but result is always the same.
If compiler says the wxString is not declared then you must include the proper header.
Declare this line, make sure it's NOT inside of #ifndef WX_PRECOMP.
#include <wx/string.h>