Undefined variables within header files - c++

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.

Related

Xcode C++ Undeclared Identifier Error

I have created a class in a header file and have listed a int rsvdtickets in the private section of the class. When trying to use this member in a function in the same header file (I am trying to add ticket prices so I am wanting to save the total under this int rsvdtickets), the compiler throws an undeclared identifier error.
I've made sure the spelling is all correct, but I am not sure how to fix this problem.
#include <iostream>
#include <math.h>
class tickets
{
public:
void getheldtickets();
void computeseats();
void availabetickets();
private:
int rsvdtickets;
int availtickets;
};
void getheldtickets()
{
int seasontkt;
int corptkt;
std::cout << "How many season ticket holders?";
std::cin >> seasontkt;
std::cout << "How many reserved corporate ticket holders?";
std::cin >> corptkt;
rsvdtickets = seasontkt + corptkt;
}
The problem is that when you have:
void getheldtickets()
{
// ..
rsvdtickets = seasontkt + corptkt;
}
You're not defining tickets::getheldtickets, you're actually declaring and defining an entirely unrelated free function called getheldtickets. That function is unrelated to the class tickets, and thus has no access to the tickets members - and so rsvdtickets is an declared identifier.
The correct way to define a class method external to the class is:
void tickets::getheldtickets()
// ^^^^^^^^^
{
// everything as before
}

Class pointer to different .h file

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.

With or without class wrappered in C++

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

C2143 error c++

Sorry for this question but I am stuck.
I have folowing syntax:
class xx
{
..some simple fields like: int t; // )))
public: class anotherClass;
xx();
MyObj* obj();
string* name(); //error C2143: syntax error : missing ';' before '*'
}
i have write # include <string>
What does compiler wants from me?!
It wants you to tell him which string. You want the standard one:
class xx
{
public:
std::string* name();
};
Now, I'm not sure why you would be returning a pointer to a string. That's a segmentation fault waiting to happen, if you ask me. Two more viable options that seem reasonable to me:
class xx
{
std::string _name;
public:
const std::string& name() const
{
return _name; // WARNING: only valid as long as
// this instance of xx is valid
}
};
or
class xx
{
public:
std::string name() const { return "hello world"; }
};
You need to either fully qualify string or bring it into the current namespace:
std::string* name();
or
using std::string;
In a header, it's generally considered bad practice to pollute the global namespace, so the first is preferred.
The compiler does not know what string is because string is residing in the namespace std, not in the global namespace. You need to change string to std::string.
In your cpp file you can use "using namespace std;" or "using std::string;" and then just write "string". But you should never use using-namespace-declarations in header files.
BTW, as the others say returning a string* is unusal, normally you would return a string.

Problems with my first CPP program - header and source

Im spending my saturday night not dressed up for halloween but rather sitting trying to learn CPP :D
anyways could someone please help me, Below I have included my source code, basically when I try compiling this form the terminal I'm getting a lot of errors, basically stating that the variables "name, ho, etc" are not declared, yet I have included my header file, so could someone pleas shave a look at this and maybe tell me what is missing? Thank you so much in advance guys!
#ifndef __TPLAYER__
#define __TPLAYER__ //prevent multiple #includes
TPlayer
{
private:
char name;
int hp;
int dmg;
int wep;
public:
TPlayer(void);
~TPlayer(void);
//Naming
void SetName(char *_name);
char GetName(void);
//Health
void SetHealth(int *_hp);
int GetHealth(void);
//Damage
int SetDamage(int *_dmp)
//Weapon
void SetWeapon(int *_wep);
int GetWeapon(void);
};
#endif /* TPlayer.h */
and here is my source file:
#include "TPlayer.h"
/////////////////
// Constructor
/////////////////
TPlayer::TPlayer(void)
{
name = "";
hp = 0;
dmg = 0;
wep = 0;
}
///////////////////
// Destructor
///////////////////
~TPlayer::TPlayer()
{
delete name;
delete hp;
delete dmg;
delete wep;
}
///////////////////
// Naming
///////////////////
void SetName(char *_name)
{
name = _name;
}
char GetName(void)
{
return *name;
}
And so forth, yet its telling me that for example, name etc has not been as shown below:
TPlayer.h:4: error: function definition does not declare parameters
TPlayer.cpp:6: error: ‘TPlayer’ has not been declared
TPlayer.cpp:6: error: ISO C++ forbids declaration of ‘TPlayer’ with no type
TPlayer.cpp: In function ‘int TPlayer()’:
TPlayer.cpp:8: error: ‘name’ was not declared in this scope
TPlayer.cpp:9: error: ‘hp’ was not declared in this scope
TPlayer.cpp:10: error: ‘dmg’ was not declared in this scope
TPlayer.cpp:11: error: ‘wep’ was not declared in this scope
TPlayer.cpp: At global scope:
TPlayer.cpp:16: error: expected class-name before ‘::’ token
TPlayer.cpp: In function ‘void SetName(char*)’:
TPlayer.cpp:30: error: ‘name’ was not declared in this scope
TPlayer.cpp: In function ‘char GetName()’:
You may want to pick up a good C++ book to learn from, as the things you're getting wrong are fundamental to the language.
Class declarations need a class keyword preceeding the class name:
class TPlayer
{
private:
// ...
You need this because the compiler needs to know if you're talking about a class or a struct or a union or an enum, etc. Otherwise you end up with lots of errors like you got.
Your member functions also need to be prefixed with TPlayer::, like how you did with the constructors and destructor. These are needed so that the compiler knows that they are part of the TPlayer class.
TPlayer::TPlayer()
{
}
TPlayer::~TPlayer()
{
}
void TPlayer::SetName(char *_name)
{
}
char TPlayer::GetName(void)
{
}
There's no need to delete class members that you didn't allocate yourself.
~TPlayer::TPlayer()
{
// These are not needed. The variables name, hp, dmg, and wep
// were allocated when you created an instance of TPlayer. These
// will go away by themselves when the destructor is called.
//delete name;
//delete hp;
//delete dmg;
//delete wep;
// The exceptions to the above rule are things that are dynamically
// allocated. For example, you must delete[] everything that
// you new[]'ed, and you must fclose() all file handles you
// get from fopen(). If you consistently use the RAII idiom,
// then you won't have to worry about these "exceptions".
}
In fact, modern C++ programs nowadays rarely need to use delete in application code. The "Resource Acquisition Is Initialization" (RAII) idiom allows you to not have to worry about delete-ing things a vast majority of the time. Standard library facilities like std::vector use the RAII idiom to manage the array memory.
Note that there are rules regarding the use of identifiers beginning with underscores. You may need to be aware of them.
For the sake of learning by example, here's an valid sample class:
foo.h
#ifndef FOO_H
#define FOO_H
class Foo
{
public:
Foo();
~Foo();
void Set(int n);
int Get() const;
private:
int n;
};
#endif
foo.cpp
#include "foo.h"
Foo::Foo() : n(0)
{
}
Foo::~Foo()
{
}
void Foo::Set(int n)
{
this->n = n;
}
int Foo::Get() const
{
return n;
}
it should be class TPlayer, not TPlayer. That will confuse the compiler and there's no telling what errors you will get after it is encountered.
Also, your member function definitions need to be prefixed by TPlayer::, i.e.,
TPlayer::SetName( const char* name ) {
// ...
}