Error: "function" is private void, error: within this context - c++

I am fairly new to C++ and I am wanting to understand why my program is giving me this error. I constructing a program that will simulate a colony of bunnies. Being able to automatically add them, give them names, ages, etc.
These are the errors that I am getting:
main2.cpp: In function ‘int main()’:
main2.cpp:109:6: error: ‘void Bunny::printBunny()’ is private
void printBunny()
^
main2.cpp:132:26: error: within this context
colony[ i ].printBunny();
^
Here is the code that I have come up with.
enter code here
#include <iostream>
#include <string>
#include <ctime>
#include <vector>
#include <cstdlib>
using namespace std;
void setSex( void );
char getSex();
void setColor( void );
string getColor();
void setAge( void );
int getAge();
void setName( void );
string getName();
void printBunny();
static const int POSSIBLE_NAMES = 5;
static const int POSSIBLE_COLORS = 4;
class Bunny
{
char sex;
string color;
int age;
string name;
bool radioactive_mutant_vampire_bunny;
BunnyData()
{
//srand( time( 0 ) );
setSex();
setColor();
setAge();
setName();
}
void setSex()
{
int randomNumber = 1 + rand() % 2;
( randomNumber == 1 ) ? sex = 'm' : sex = 'f';
}
char getSex()
{
return sex;
}
void setColor()
{
//color = possibleColors[ 0 + rand() % POSSIBLE_COLORS ];
}
string getColor()
{
return color;
}
void setAge()
{
age = 0;
}
int getAge()
{
return age;
}
void setName()
{
//name = possibleNames[ 0 + rand() % POSSIBLE_NAMES ];
}
string getName()
{
return name;
}
void printBunny()
{
cout << "Name: " << getName() << endl;
cout << "Sex: " << getSex() << endl;
cout << "Color: " << getColor() << endl;
cout << "Age: " << getAge() << endl;
}
};
int main()
{
vector< Bunny > colony;
cout << "Welcome to Bunny Graduation!" << endl << endl;
for( int i = 0; i < 5; ++i )
{
colony.push_back( Bunny() );
}
for( int i = 0; i < 5; ++i )
{
colony[ i ].printBunny();
cout << endl;
}
return 0;
}

Everything in a class has private access unless stated otherwise For example,
class access
{
int iAmPrivate; // private. Not accessible outside of the class
public:
int getValue() //public and accessible to all
{
return iAmPrivate;
}
int iAmPublic; //also public
}
Documentation on access levels.

You need to declare them to be public, if you don't, these members are private by default, which means you cannot invoke them outside the class.
class Bunny
{public:
void printBunny() {...}
};
You really need to consider which class access modifier you should apply to the member, because normally, we don't use just one type of access modifier in OO.
You can check this site to learn more about it.

In your class:
class Bunny
{
char sex;
string color;
int age;
string name;
// Rest of class fields ...
}
All the fields are private by default. This is because you have not used the keyword public: before you declare the fields of the class Bunny. As a result, you cannot invoke/call these fields and functions outside of the class, as you have tried in:
colony[ i ].printBunny(); // you are calling a private member of class Bunny outside of the class
There are 2 ways to get around this error:
One way is that you can declare the class members as public. This will allow the functions and fields to be invoked outside of the class:
class Bunny
{
public: // declare all fields of the class as public
char sex;
string color;
int age;
string name;
// Rest of class fields ...
}
Another thing you can do is declare Bunny as a struct instead if a class. This way, all your fields sill be accessible outside the struct:
struct Bunny
{
char sex;
string color;
int age;
string name;
// Rest of class fields ...
}

Related

How do you make an object as a parameter for a function c++

I am trying to make an object as a parameter for my add() function in this code:
class EnterInfo
{
protected:
string name;
int age;
string birthmonth;
public:
EnterInfo()
{
}
EnterInfo(string n, int a, string b)
{
name = n;
age = a;
birthmonth = b;
}
};
class CourseInfo
{
protected:
string title;
public:
CourseInfo()
{
}
CourseInfo(string t)
{
title = t;
}
void add()
{
}
};
int main()
{
EnterInfo s1;
CourseInfo c1;
s1 = EnterInfo("Sand", 20, "Jan");
c1 = CourseInfo(" x Records");
}
I want the add() function to gather all the data from the object "s1" and compact it into an array that I can access later. I could add, remove, or edit the data moving forward or even maybe make a new object "c2" which contains "y records" with the same s1 values ("sand", 20, "Jan"), however, I have no idea how to implement this in code.
c1.add(s1); // assume s1 (EnterInfo): Sand 20 Jan
c1.add(s2); // assume s2 (EnterInfo): Paul 23 Aug
this is the code I want to work with. I don't know how to make it work though. The end game would be this
c1.print();
output:
x records
Sand 20 Jan
Paul 23 Aug
create a vector of EnterInfo objects and put it in CourceInfo class. The code below does what you need:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class EnterInfo
{
public:
string name;
int age;
string birthmonth;
EnterInfo()
{
name = "";
age = 0;
birthmonth = "";
}
EnterInfo(string n, int a, string b)
{
name = n;
age = a;
birthmonth = b;
}
};
class CourseInfo
{
protected:
string title;
vector<EnterInfo> info_vec;
public:
CourseInfo()
{
title = "";
}
CourseInfo(string t)
{
title = t;
}
void add(const EnterInfo enterInfo)
{
this->info_vec.push_back(enterInfo);
}
void print() {
cout << this->title << endl;
for (const auto& it : this->info_vec) {
cout << it.name << " " << it.age << " " << it.birthmonth << endl;
}
}
};
int main()
{
EnterInfo s1("Sand", 20, "Jan");
EnterInfo s2("Arash", 21, "Feb");
CourseInfo c1(" x Records");
c1.add(s1);
c1.add(s2);
c1.print();
}
Side notes:
1- It's better to assign default values to the members of your class in the constructor.
2- I changed the access level of your EnterIndo members into public in order to use them in add function but the standard way is to set them to private and create getters and setters for them.
Research about std::vector and get/setters if you are not familiar with them.

Class Employee ID count c++ [duplicate]

This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 4 years ago.
I'm editing it, now ok i apply an empty constructor and my code worked but this way:
Name1 SName1 1000 0.2 100
Name2 SName2 1000 0.3 750
This code normally works perfectly and my teacher especially wants us to use "this->" and "*this" so here's my code:
my .h file
#ifndef COMEMPLOYEE_H
#define COMEMPLOYEE_H
#include <string>
using namespace std;
class ComEmployee
{
protected:
string firstName;
string lastName;
static int ID;
double grossSale;
double comRate;
public:
ComEmployee();
ComEmployee(string, string, double, double);
ComEmployee& setfirstName(string);
ComEmployee& setlastName(string);
ComEmployee& setgrossSale(double);
ComEmployee& setcomRate(double);
string getfirstName();
string getlastName();
double getgrossSale();
double getcomRate();
int getID() const;
double calCom() const;
void Display() const;
};
#endif
my .cpp file
#include "ComEmployee.h"
#include <iostream>
using namespace std;
int ComEmployee::ID = 1000;
ComEmployee::ComEmployee(){}
ComEmployee::ComEmployee(string name, string lname, double gs, double comr)
{
this->firstName = name;
this->lastName = lname;
this->grossSale = gs;
this->comRate = comr;
++ID;
}
int ComEmployee::getID() const
{
return ID;
}
ComEmployee & ComEmployee::setfirstName(string name)
{
firstName = name;
return *this;
}
ComEmployee & ComEmployee::setlastName(string lname)
{
lastName = lname;
return *this;
}
ComEmployee & ComEmployee::setgrossSale(double gs)
{
grossSale = gs;
return *this;
}
ComEmployee & ComEmployee::setcomRate(double comr)
{
comRate = comr;
return *this;
}
string ComEmployee::getfirstName()
{
return firstName;
}
string ComEmployee::getlastName()
{
return lastName;
}
double ComEmployee::getgrossSale()
{
return grossSale;
}
double ComEmployee::getcomRate()
{
return comRate;
}
double ComEmployee::calCom() const
{
return grossSale*comRate;
}
void ComEmployee::Display() const
{
cout << firstName << " " << " " << getID() << " " << comRate << " " << calCom() << endl;
}
here's my main.cpp file
#include <iostream>
#include "ComEmployee.h"
using namespace std;
int main()
{
ComEmployee employee, employee2;
employee.setfirstName("Name1").setlastName("SName1").setgrossSale(500).setcomRate(0.2).Display();
employee2.setfirstName("Name2").setlastName("SName2").setgrossSale(2500).setcomRate(0.3).Display();
system("pause");
}
I want my output as:
Name1 SName1 1001...
Name2 SName2 1002...
You have to change your design a bit. As ID is employee ID, it cannot be a static variable. A static variable belongs to the class rather than to particular instance of
the class.
Define ID as a normal member of the class.
You can use a new static variable CurrentID instead to keep track of the employees.
After defining it like below,
int ComEmployee::CurrentID = 1000;
In the default and non-default constructors, do the following:
this->ID = CurrentID++;
Add some int variable to your class definition:
int m_ID;
Then, you need to emplement a default constructor in cpp-file:
// cpp
ComEmployee::ComEmployee()
{
m_ID = ID++;
}
And modify your GetID function:
int ComEmployee::GetID() const
{
return m_ID;
}

How can I assign class object into a class

I need to creat an object Pokemon in the main()
that assign it into the class PokemonWorld, and let the PokemonWolrd to decide which PokemonStation is this Pokemon need to go
I tired get the data separatly (get name and hp) and get together(get a Pokemon class)
but both fail
#include <iostream>
#include <cstring>
#include <iomanip>
using namespace std;
class Pokemon {
public:
Pokemon() {};
Pokemon(char x[], int n) {
strncpy_s(name, x, 10);
hp = n;
};
private:
char name[10];
int hp;
};
class PokemonStation {
private:
Pokemon **list= new Pokemon*[1000];
public:
PokemonStation() {};
PokemonStation(int x) {
id = x;
};
int id;
void assigntoList(int i,Pokemon x)
{
if (i > 0)
i--;
list[i] = new Pokemon(x);
cout << "creat" << list[i];
};
};
class PokemonWorld {
private:
char name[10];
public:
PokemonStation s1;
PokemonStation s2;
PokemonWorld() {};
PokemonWorld(char x[], int y=1, int z=2) {
strncpy_s(name, x, 10);
PokemonStation s1(y);
PokemonStation s2(z);
};
const char* const getName() const{
return name;
};
void assigntoStation(int i,Pokemon x) {
if (i == 0 || i % 2 == 0)
s1.assigntoList(i, x);
else
s2.assigntoList(i, x);
};
};
void main() {
int number,hp,i;
char name[10];
cout << "What is the World Name ?" <<endl;
cin >> name;
PokemonWorld world(name);
cout << "Please input the number of Pokemon in the " << world.getName() <<" world:" << endl;
cin >> number;
Pokemon **mon = new Pokemon*[number];
cout << "Please input the characteristics of all Pokemon: Name HP" << endl;
for (i = 0;i < number;i++)
{
cin >> name >> hp;
mon[i] = new Pokemon(name, hp);
world.assigntoStation(i,*(mon[i]));
}
for (i = 0;i < number;i++)
cout << "world is " << world.getName() << endl;
system("pause");
};
In C++, you should use std::vectors for dynamic lists of things and std::strings for text. If you know Java, these are like ArrayList and String. (To use these, make sure you #include <vector> and <string>.)
For instance, your Pokemon class, rewritten with name as a string:
class Pokemon {
public:
Pokemon() {}
Pokemon(string name, int hp):name(name), hp(hp) { // construct the fields directly
}
private:
string name;
int hp;
};
And your PokemonStation class, rewritten using a vector for the list of Pokemon:
class PokemonStation {
private:
vector<Pokemon> list;
public:
PokemonStation() {}
PokemonStation(int x):id(x) {}
int id;
void assignToList(Pokemon x)
{
list.push_back(x); // add x to the list
}
};
If you want to print a Pokemon with cout <<, then you'll have to overload the << operator to define what gets printed. Add this into your class:
class Pokemon {
public:
...
friend ostream& operator<<(ostream& out, const Pokemon& p) {
out << p.name; // just print the name
return out;
}
...
};
Just make sure that you're couting a Pokemon, not a pointer-to-Pokemon (Pokemon*), and you won't get an address.

Inheriting private members from base class to derived classes c++

I'm trying to inherit the name,skeletonType, and numLegs from my base class to my derived class.
I have a base class named Invertebrates and derived class named Spider. I want to be able to use the private variables with the derived class from my base class. I keep getting a compiling error on line 47 and it says expected primary-expression before ','.
I'm trying to get my output to look like this:
Spider:Brown Recluse, number of legs = 8, skeleton type = EXOSKELETON
Could someone help me out and point me in the right direction please. Here is what I put together so far.
// invertebrates.h
// invertebrate specifications
#ifndef _INVERTEBRATE_H_
#define _INVERTEBRATE_H_
#include <iostream>
using namespace std;
enum Skeleton_Type { NONE, HYDROSTATIC, EXOSKELETON };
class Invertebrate {
private:
string name;
Skeleton_Type skeletonType;
int numLegs;
protected:
void setSkeletonType(Skeleton_Type skeletonType);
void setNumLegs(int numLegs);
public:
Invertebrate();
Invertebrate(string name, Skeleton_Type skeletonType, int numLegs);
string getName();
Skeleton_Type getSkeletonType();
int getNumLegs();
virtual void print() = 0;
};
class Spider : public Invertebrate {
private:
const string NAME_PREFIX = "Spider: ";
public:
Spider();
Spider(string name);
virtual void print();
};
#endif // _INVERTEBRATE_H_
**********************************************************************
//invertebrates.cpp
#include "invertebrate.h"
void Invertebrate::setSkeletonType(Skeleton_Type skeletonType)
{
this->skeletonType = skeletonType;
}
void Invertebrate::setNumLegs(int numLegs)
{
this->numLegs = numLegs;
}
Invertebrate::Invertebrate()
{
name = "noName";
skeletonType = NONE;
numLegs = 0;
}
Invertebrate::Invertebrate(string name, Skeleton_Type skeletonType, int numLegs)
{
this->name = name;
this->skeletonType = skeletonType;
this->numLegs = numLegs;
}
string Invertebrate::getName()
{
return this->name;
}
Skeleton_Type Invertebrate::getSkeletonType()
{
return this->skeletonType;
}
int Invertebrate::getNumLegs()
{
return this->numLegs;
}
Spider::Spider(string name):Invertebrate(name,EXOSKELETON,8)
{
name = Invertebrate::getName();
}
void Spider::print()
{
string strSkType = "";
if(this->getSkeletonType() == 0)
strSkType= "none";
else if(this->getSkeletonType() == 1)
strSkType= "Hydrostatic";
else if(this->getSkeletonType() == 2)
strSkType= "exoskeleton";
cout << this->NAME_PREFIX + getName();
cout << ", number of legs = " << this->getNumLegs() << ", skeleton type = " << strSkType << endl;
}
int main()
{
Spider *sp = new Spider("Brown Recluse");
sp->print();
return 0;
}
OUTPUT:
Here are the issues in your code :-
In .h file -
const string NAME_PREFIX = "Spider: ";
is not a valid way to initialize cont members - const should be initialized through constructor initializer list (till C++11).
Correct way in .cpp
Spider::Spider(string name):NAME_PREFIX(name),Invertebrate(name,EXOSKELETON,8)
{
name = NAME_PREFIX + Invertebrate::getName();
}
In the same constructor you have written name&, which is wrong, just pass name.
Spider::Spider(string
name):NAME_PREFIX(name),Invertebrate(name,EXOSKELETON,8)
I think I finally discovered what your line 47 is:
Spider::Spider(string name):Invertebrate(name&,EXOSKELETON,8)
{
name = NAME_PREFIX + Invertebrate::getName();
}
This function has two problems:
What is that & in name&? That is not valid syntax!
You cannot access this->name directly, because it is private in the base class. Instead here you are modifying the local name argument, and that does nothing useful.
You could make the base name public or protected. Or you could add a setName() protected function.
But in my opinion this member is ok being private and read-only. The solution would be to specify the proper name at construction time:
Spider::Spider(string name)
:Invertebrate(NAME_PREFIX + name, EXOSKELETON, 8)
{
}

Cannot call getter method unless specifying "this" keyword

Why does the example from a tutorial page works without having the this keyword in the constructor?
The code from the website:
#include <iostream>
using namespace std;
class Rectangle {
int width, height;
public:
Rectangle ();
Rectangle (int,int);
int getWidth() {
return width;
}
};
Rectangle::Rectangle () {
width = 5;
height = 5;
}
Rectangle::Rectangle (int a, int b) {
width = a;
height = b;
}
int main () {
Rectangle rect (3,4);
Rectangle rectb;
cout << "rect area: " << rect.getWidth() << endl;
cout << "rectb area: " << rectb.getWidth() << endl;
return 0;
}
My code:
class Person {
int age;
std::string name;
public:
Person();
Person(int, std::string);
std::string * getName() {
return &name;
}
int * getAge() {
return &age;
}
};
Person::Person () {
age = 25;
name = "John";
}
Person::Person (int age, std::string name){
// This is the part :
this->age = age;
this->name = name;
}
int main() {
Person john(45, "Doe");
printf("Name %d \n", *john.getAge() );
std::cout << "Age " << *john.getName() << std::endl;
return 0;
}
As you can see in my code i must use this->name, if I don't then the values are not assigned.
On the other hand, the example code from the website works with or without this->
Why does this happen?
The problem is that the parameters of the function have the same name as the class so the compiler doesn't know which one you are talking about unless you use this. You can solve this by changing the names of the variables or you could use a member initialization list
Person::Person (int age, std::string name) : name(name), age(age) {}
As a note I like to use the same name as the class variable but add a _ after the name to make it different. So in this case I would have done:
Person::Person (int age_, std::string name_) : name(name_), age(age_) {}
This makes it easier to differentiate between the class members and the constructor parameters.
Person::Person (int age, std::string name){
// This is the part :
this->age = age;
this->name = name;
}
Because your private variable is called name, and the variable you send in is also called name, you use this-> to specify which variable called name you are using.