I'm studying for pointer and inheritance of C++.\
I made pointer of vector Employee class which has name and salary in it.
Also, it has print function which printout name and salary.
I made it virtual
virtual void print() const;
Also here's the implementation of function
void Employee::print() const
{
cout << "Inquiry Employee info..." << endl;
cout << "Name:" << get_name() << "\n";
cout << "Salary:" << get_salary() << "\n" << "\n";
}
In derived class, I added one more private data Department Name and override print function.
I put derived class in pointer vector, and tried to call the function on derived function.
However, it only calls the function in base class.
When I make derived class object itself and called that print function, it worked.
What should I change to make derived class object in base class pointer vector can call function in derived class?
Addition ##
#ifndef MANAGER_H
#define MANAGER_H
#include <string>
#include<iostream>
#include "ccc_empl.h"
#include <iomanip>
class Manager : public Employee
{
public:
Manager();
Manager(string name, double salary, string dept);
~Manager();
virtual string get_department() const;
void print();
private:
string deptName;
};
#endif
implementation
#include <iostream>
#include <string>
#include "manager.h"
#include "ccc_empl.h"
Manager::Manager(){}
Manager::Manager(string name, double salary, string dept)
: Employee(name,salary)
{
deptName = dept;
}
Manager::~Manager(){}
string Manager::get_department() const
{
return deptName;
}
void Manager::print()
{
cout << "Inquiry Manager info..." << endl;
cout << "Name:" << get_name() << "\n";
cout << "Salary:";
cout << get_salary() << "\n";
cout << "Department:"<< get_department() << endl << endl;
}
You haven't shown us the Derived class print function, but I would guess that you forgot to declare it const. Easy mistake to make.
Related
y'all I'm having an issue trying to access the member functions of an object that I have stored in an array of pointers full of objects.
Header:
#ifndef COURSEGRADES__H
#define COURSEGRADES__H
#include "Essay.h"
#include "FinalExam.h"
#include "PassFailExam.h"
#include "GradedActivity.h"
class CourseGrades:public Essay, public FinalExam, public PassFailExam, public GradedActivity
{
public:
CourseGrades();
void setLab(GradedActivity &l);
void setPassFailExam(PassFailExam &pf);
void setEssay(Essay &e);
void setPassFailFinal(FinalExam &fe);
void print();
private:
GradedActivity *grades[4];
};
#endif // COURSEGRADES_H
CPP
#include "CourseGrades.h"
#include <iostream>
CourseGrades::CourseGrades()
{
//ctor
}
void CourseGrades::setLab(GradedActivity &l)
{
grades[0] = &l;
}
void CourseGrades::setPassFailExam(PassFailExam &pf)
{
grades[1] = &pf;
}
void CourseGrades::setEssay(Essay &e)
{
grades[2] = &e;
}
void CourseGrades::setPassFailFinal(FinalExam &fe)
{
grades[3] = &fe;
}
void CourseGrades::print()
{
std::cout << grades[0]->getScore() << "\t" << grades[0]->getLetterGrade() << std::endl;
std::cout << grades[1]->getScore() << "\t" << grades[1]->getLetterGrade() << std::endl;
std::cout << grades[2]->getScore //this function exists in the Essay class but I can't access it from here.
}
So I'm trying to access the third object in the grade array which is an object of the essay class which includes a unique function that is separate from the get score function in the GradeActivity class. I'll also need to access its unique getLetterGrade method but once I get one I should be able to find out how to get the other. Any help would be greatly appreciated.
I keep getting an error saying:
initializing cannot convert from 'const char *' to 'Address'
I am trying to allow my Person class to use Address as a parameter in the constructor. I'm including my Address header file in the Person header file so I don't know what I'm doing wrong. Also there's nothing in my .cpp file besides calling the default constructor Person myPerson.
Address header file:
#ifndef ADDRESSMODEL
#define ADDRESSMODEL
#define ADDRESSDEBUG
#include <iostream>
#include <string.h>
using namespace std;
class Address {
public:
Address(void);
Address(char* aNumber,
char* aStreetName,
char* aTownName,
char* aCounty);
~Address();
void setAddress(char* aNumber,
char* aStreetName,
char* aTownName,
char* aCounty);
char* getNumber(void);
char* getStreetName(void);
char* getTownName(void);
char* getCounty(void);
protected:
private:
char theNumber[4];
char theStreetName[20];
char theTownName[20];
char theCounty[20];
};
inline Address::Address(void) {
char theNumber[] = "0";
char theStreetName[] = "0";
char theTownName[] = "0";
char theCounty[] = "0";
cout << "\n Default constructor was called" << endl;
}
inline Address::Address(char* aNumber,
char* aStreetName,
char* aTownName,
char* aCounty) {
strcpy(theNumber, aNumber);
strcpy(theStreetName, aStreetName);
strcpy(theTownName, aTownName);
strcpy(theCounty, aCounty);
cout << "\n Regular constructor was called" << endl;
}
inline Address::~Address() {
cout << "\n Deconstructor was called" << endl;
}
#endif // ifndef ADDRESSMODEL
My Person header:
#include "Date.h"
#include <iostream>
#include <string.h>
using namespace std;
class Person {
public:
Person(void);
// Person(Address anAddress);
protected:
private:
// Name theName;
// Date theDate;
Address theAddress;
};
inline Person::Person(void) {
Address theAddress = ("00", "000", "00", "00");
cout << "\n The default constructor was called" << endl;
}
// inline Person :: Person(Address anAddress) {
// cout << "\n The regular constructor was called" << endl;
// }
#endif
First of All re-check if you are including the correct header file in the person Class , I think you have included the "Date.h" which might not be the correct file, You should check it Again.
Then in the constructor of Person class you are re-declaring the theAddress Attribute which is already declared as the private attribute.
it should be something like this:
#include "Date.h"
#include <iostream>
#include <string.h>
using namespace std;
class Person
{
public:
Person(void);
//Person(Address anAddress);
protected:
private:
//Name theName;
//Date theDate;
Address theAddress;
};
inline Person :: Person(void)
{
theAddress = ("00","000","00","00");
cout << "\n The default constructor was called" << endl;
}
you can't call the constructor and re-declare the attribute again.
You should use constructor initializer list instead to call the required constructor of Address class.
A little weird prob;em i came across when working on something that I got stuck with and I have no idea why this happens.
So i have 2 files (actually way more but those arent important) called Employee and Keeper. Employee is the base class while Keeper is the derived class.
The employee has several attributes and a method called saveFile and the keep inherits these.
Employee.h:
protected:
const int number;
const std::string name;
int age;
// All ordinary employees
Employee *boss = nullptr; // works for ...
public:
void saveFile(std::ostream&) const;
Keeper.cc
void Keeper::saveFile(ostream& out) const
{
out << "3\t3\t"
<< number << "\t" << name << "\t" << age
// The error happen here on boss->number
<< "\t" << cage->getKind() << "\t" << boss->number << endl;
}
Keeper.h (full code)
#ifndef UNTITLED1_KEEPER_H
#define UNTITLED1_KEEPER_H
#include "Employee.h"
// tell compiler Cage is a class
class Cage;
#include <string> // voor: std::string
#include <vector> // voor: std::vector<T>
#include <iostream> // voor: std::ostream
class Keeper : public Employee {
friend std::ostream& operator<<(std::ostream&, const Keeper&);
public:
Keeper(int number, const std::string& name, int age);
~Keeper();
/// Assign a cage to this animalkeeper
void setCage(Cage*);
/// Calculate the salary of this employee
float getSalary() const;
/// Print this employee to the ostream
void print(std::ostream&) const;
// =====================================
/// Save this employee to a file
void saveFile(std::ostream&) const;
protected:
private:
// Keepers only
Cage *cage = nullptr; // feeds animals in ...
};
Now i get the error on the const int number from the employee.h when i call boss->number in the saveFile method.
The error is on this line:
<< "\t" << cage->getKind() << "\t" << boss->number << endl;
because of boss->number
I have no idea why this happens and everywhere I read it said it should compile just fine but it doesnt.
Can anyone help?
Thank you~
The number member of the boss object is protected from direct access by functions outside of the object itself, even when owned by an object of the same type. The exceptions would be friend classes and methods, and copy constuctors.
In response to a comment: Inheritance is not your problem. The data in the object itself is protected from outside access. Your Keeper object inherits its own number member that it can access, as well as a pointer to a boss Employee. To fix your problem you can either make number public, or add an access method to return the value.
I am trying to make a simple friend function work, but not in just one source file. I seem to get an error and I can't seem to find an answer why.
Please have a look at my code:
----------classOne.h--------------
#ifndef CLASSONE_H_
#define CLASSONE_H_
using namespace std;
class ClassOne {
private:
int m_a;
int m_b;
public:
ClassOne(int a, int b);
void printValuesOne();
friend void ClassTwo::twoPrintsOne();
};
-
----------classOne.cpp------------
#include <iostream>
#include "classOne.h"
using namespace std;
ClassOne::ClassOne(int a, int b) {
m_a = a;
m_b = b;
}
void ClassOne::printValuesOne() {
cout << "m_a: " << m_a << " " << "m_b: " << m_b << endl;
}
.
----------classTwo.h-------------
#ifndef CLASSTWO_H_
#define CLASSTWO_H_
using namespace std;
class ClassTwo {
private:
int m_c;
int m_d;
public:
ClassTwo(int c, int d);
void printValuesTwo();
twoPrintsOne();
};
#endif
-
---------classTwo.cpp-----------
#include <iostream>
#include "classTwo.h"
using namespace std;
ClassTwo::ClassTwo(int c, int d) {
m_c = c;
`enter code here`m_d = d;
}
void ClassTwo::printValuesTwo() {
cout << "m_c: " << m_c << " " << "m_d: " << m_d << endl;
}
void twoPrintsOne() {
cout << "ClassTwo: " << m_a: " << m_a << " " << "m_b: " << m_b << endl;
}
Basically ClassOne and ClassTwo are the same sort of thing, but only one of ClassTwo's method has access to all of ClassOne's members, so ClassTwo can print ClassOne's member variables. However, when I try to compile the whole program (I haven't provided the main method here), I get this error an error:
classOne.h:19:15: error: ‘ClassTwo’ has not been declared
friend void ClassTwo::twoPrintsOne();
^
Can someone help and explain?
ClassOne doesn't know about ClassTwo, therefore it cannot befriend with any of its methods. You have to add:
#include "classTwo.h"
on top of your classOne.h.
You are getting confused with what "friend" is supposed to do.
"friending" ClassTwo will allow ClassTwo to access the private members of ClassOne as if they were public.
It will not link those members between the two classes in any way.
You could have ClassTwo inherit from ClassOne, or add a ClassOne member in ClassTwo
I'm a relative beginner to C++, I've been learning for the past 4 months. We have an an assignment to do for school; create a text based adventure game using what we have learnt so far from C++. We went over classes, inheritance and pointers today so I thought that I'd get some practice using classes/inheritance.
My code so far is:
Character.h (The header file)
#ifndef CHARACTER_H
#define CHARACTER_H
#include <cstdlib>
class Character
{
private:
int Health;
public:
Character();
~Character();
int GetHealth() {return Health;}
void SetHealth(int newHealth) {Health = newHealth;}
};
class Monster:public Character
{
int GetHealth() {return Health;}
void SetHealth(int newHealth) {Health = rand()% 50+100;}
}
#endif
Character.cpp
#include "Character.h"
Character::Character()
{
Health = 100;
}
Character::~Character()
{
}
Battle.cpp (Where everything takes place)
#include <iostream>
#include <cstdlib>
#include "Character.h"
using namespace std;
int main()
{
Character* Player = new Character();
Monster* Monster1 = new Monster();
cout << "Player's Health is: " << Player->SetHealth << endl << endl;
cout << "Monster's Health is: " << Monster1->SetHealth << endl << endl;
}
Let me explain what I'm trying to do...
I'm simply trying to get the program to display the health of both the player and the monster.
In the character header file, the class 'Character' is a base for every character in the game. Then I Get and Set the health for the class. Then I'm trying to create a child class called 'Monster' derived from the 'Character' class. This will have different health compared to the standard character class but I'm not sure how to do that. I wanted to make the health randomly generate between 50 and 100. Then in the 'Battle.cpp' file I am trying to create a new character called 'Player' which includes the default amount of health (which is 100) and a new monster called 'Monster1'. Then I want to display the health for both characters. I also aim to create multiple monsters with varying amounts of health.
When I try to run the program I seem to get a large amount of errors saying 'See declaration of Character::Health'.
I'm not too sure what I've done wrong as I'm still fairly new to C++ and still trying to get my head around the concepts of pointers and inheritance.
Let me answer inside the code:
#ifndef CHARACTER_H
#define CHARACTER_H
#include <cstdlib>
class Character
{
// this property will be used in the derived classes, we need protected instead of private
protected:
int Health;
public:
Character();
~Character();
// This method is to be repeated in the derived class, and publicly accessible
// (not only inside the class, but also outside (like you do in main())
public:
int GetHealth() {return Health;}
// This method needs to be redefined in Monster, that's a candidate for a virtual method
virtual void SetHealth(int newHealth) {Health = newHealth;}
};
class Monster:public Character
{
// You don't need this anymore - the GetHealth from class Character is accessible
// int GetHealth() {return Health;}
// you override a method - write a different version. Use virtual to note that
virtual void SetHealth(int newHealth) {Health = rand()% 50+100;}
}; // lacked a semi-colon here :)
#endif
And the code for Battle.cpp
#include <iostream>
#include <cstdlib>
#include "Character.h"
using namespace std;
int main()
{
Character* Player = new Character();
Monster* Monster1 = new Monster();
// The moment you cout, you need to provide a value (a method that returns something).
// You want to "GetHealth()" in order to show it :)
cout << "Player's Health is: " << Player->GetHealth() << endl << endl;
cout << "Monster's Health is: " << Monster1->GetHealth() << endl << endl;
}
I also don't like what you do with Health in the class. First you declare it private - so nobody can change it in an unauthorized way. Then you declare a plain SetHelth() which lets you do anything with the value.
Instead you could make a initial value in the constructor:
#ifndef CHARACTER_H
#define CHARACTER_H
#include <cstdlib>
class Character
{
// this property will be used in the derived classes, we need protected instead of private
protected:
int Health;
public:
Character();
~Character();
// This method is to be repeated in the derived class, and publicly accessible
// (not only inside the class, but also outside (like you do in main())
public:
int GetHealth() {return Health;}
};
class Monster:public Character
{
// You don't need this anymore - the GetHealth from class Character is accessible
// int GetHealth() {return Health;}
public:
Monster();
}; // lacked a semi-colon here :)
#endif
And the Character.cpp
#include "Character.h"
Character::Character()
{
Health = 100;
}
Character::~Character()
{
}
Monster::Monster()
{
Health = rand()% 50+100;
}
And then you can change it with methods like DrinkHealthPotion(); or GetDamage();
I think your problem might be a typo, where you have written:
cout << "Player's Health is: " << Player->SetHealth << endl << endl;
cout << "Monster's Health is: " << Monster1->SetHealth << endl << endl;
I believe you mean GetHealth and not SetHealth, also GetHealth is a function so you will have to call it with parenthesis GetHealth().
So I believe that you want it to say:
cout << "Player's Health is: " << Player->GetHealth() << endl << endl;
cout << "Monster's Health is: " << Monster1->GetHealth() << endl << endl;
Hope that helps, and good luck with your future endeavors with C++