How to reuse variables from the base class to the derived class - c++

I am working on a project to show statistics for a generic vehicle, then for a car and a truck.
All of the objects have a Manufacturer and Model Year, but the Car has a number of doors, and the truck has a towing capacity.
I have my vehicle class and class constructors all working properly in the code.
Now I want to call the same method of data storage from the base class Vehicle, and use it for the Car Class.
#pragma once
#include <iostream>
#include <string>
using namespace std;
class Vehicle {
private:
string manu;
int year;
public:
// Default constructor
Vehicle() {
manu = "";
year = 0;
}
// Constructor
Vehicle(string autoManu, int autoYear) {
manu = autoManu;
year = autoYear;
}
// Accessors
string getManu() const { return manu; }
int getModel() const { return year; }
void storeInfo(string autoManu, int autoYear);
void displayInfo();
};
This is my Vehicle.h file ^
#include "Vehicle.h"
void Vehicle::storeInfo(string autoManu, int autoYear) {
manu = autoManu;
year = autoYear;
}
void Vehicle::displayInfo() {
cout << "Manufacturer- " << manu << endl;
cout << "Make Year- " << year << endl;
}
This is my Vehicle.cpp file ^
These both work perfectly, now I want to use the same kind of displayInfo for the Car class.
#pragma once
#include <iostream>
#include "Vehicle.h"
#include <string>
using namespace std;
// The Car class represents a car.
class Car : public Vehicle {
private:
int doors;
public:
// Default constructor
Car() : Vehicle() { doors = 0; }
// Constructor #2
Car(string carManu, int carYear, int carDoors) : Vehicle(carManu, carYear) {
doors = carDoors;
}
// Accessor for doors attribute
int getDoors() { return doors; }
void storeInfo(string autoManu, int autoYear, int carDoors);
void displayInfo();
};
This is my Car.h file ^
#include "Car.h"
void Car::storeInfo(string autoManu, int autoYear, int carDoors) {
manu = autoManu;
year = autoYear;
doors = carDoors;
}
void Car::displayInfo() {
cout << "Manufacturer- " << manu << endl;
cout << "Make Year- " << year << endl;
cout << "Doors on the Car" << doors << endl;
}
This is the Car.cpp file.
The issue I am encountering is that the menu and year variables, the variables defined in the base class, are saying "Vehicle::manu is inaccessible"
What would be causing this, and what is the fix?
Thanks!

Related

How do I pass arguments needed by the base class constructor when invoking the derived class?

When i try to initialize a variable that is type of derived class it gives me an error when i try to input the field from the base class.
this is from base class.
osoba(string ime)
{
this->ime = ime;
}
This is from derived calss:
profesor(string zvanje) : osoba(ime)
{
this->zvanje = zvanje;
}
This is from the main code:
profesor prof("Mika", "Direktor");
The error is on the first atribute "Mika".
I just can't seem to understand how to make it so that i can construct a derived class variable that can let me input the field from the base class.
This is the full code:
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
class osoba
{
public:
string ime;
osoba(string ime)
{
this->ime = ime;
}
virtual void pisi()
{
cout << "Ime osobe je:" << this->ime << endl;
}
};
class student : public osoba
{
string indeks;
public:
student(string indeks) : osoba(ime)
{
this->indeks = indeks;
}
void pisi()
{
osoba::pisi();
cout << "Indeks je:" << this->indeks << endl;
}
};
class profesor : public osoba
{
string zvanje;
public:
profesor(string zvanje) : osoba(ime)
{
this->zvanje = zvanje;
}
void pisi()
{
osoba::pisi();
cout << "Zvanje profesora je:" << this->zvanje << endl;
}
};
int main()
{
int i; profesor prof("Mika", "Direktor");
cin >> i;
return 0;
}

How to declare a default constructor for subclass?

Very recently, I have started learning C++ full-time.
It is my understanding that constructors in C++ are not inherited by subclasses, and therefore must be declared in the subclass.
Below, I have a program that has a base class Car with a default constructor using default values for the 3 variables, then I have a subclass SportsCar that supposedly invokes the default constructor from the base class.
My problem is that I am having trouble figuring out a way to initialize the new variable acceleration for the subclass constructor to a value such as -2.
Here is my .h file
#include <iostream>
#include <string>
using namespace std;
#ifndef CAR_H_
#define CAR_H_
class Car {
public:
Car();
void SetName(string carName);
void SetMPH(int carMPH);
void SetPrice(double carPrice);
string GetName() const;
int GetMPH() const;
double GetPrice() const;
virtual void display() {
cout << "Car Information: " << endl;
cout << "Model Name: " << name << endl;
cout << "Top Speed: " << mph << " miles per hour" << endl;
cout << "Sales Price: $" << price << endl;
}
void SetInfo(string theName, int theMPH, double thePrice) {
name = theName;
mph = theMPH;
price = thePrice;
}
virtual ~Car() {
cout << "deletion complete" << endl;
}
private:
string name;
int mph;
double price;
};
Car::Car() {
name = "NoName";
mph = -1;
price = 0.0;
}
void Car::SetName(string carName) {
name = carName;
}
void Car::SetMPH(int carMPH) {
mph = carMPH;
}
void Car::SetPrice(double carPrice) {
price = carPrice;
}
string Car::GetName() const {
return name;
}
int Car::GetMPH() const {
return mph;
}
double Car::GetPrice() const {
return price;
}
class SportsCar : public Car {
public:
void SetAcceleration(double carAcceleration) {
acceleration = carAcceleration;
}
double GetAcceleration() const {
return acceleration;
}
void display() override {
Car::display();
cout << "0-60mph Acceleration: " << acceleration << endl;
}
private:
double acceleration;
};
#endif /* CAR_H_ */
Here is my .cpp file:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
#include "Car.h"
int main() {
Car* nullCar;
Car* regularCar1;
Car* regularCar2;
SportsCar* nullSportsCar;
vector<Car*> carsList;
unsigned int i;
nullCar = new Car();
carsList.push_back(nullCar);
regularCar1 = new Car();
regularCar1->SetName("2022 Honda Civic");
regularCar1->SetMPH(140);
regularCar1->SetPrice(22550.79);
carsList.push_back(regularCar1);
regularCar2 = new Car();
regularCar2->SetInfo("2022 Nissan Altima", 130, 24900.49);
carsList.push_back(regularCar2);
nullSportsCar = new SportsCar();
carsList.push_back(nullSportsCar);
for (i = 0; i < carsList.size(); i++) {
carsList.at(i)->display();
cout << endl;
}
return 0;
}
Here is the output:
Car Information:
Model Name: NoName
Top Speed: -1 miles per hour
Sales Price: $0
Car Information:
Model Name: 2022 Honda Civic
Top Speed: 140 miles per hour
Sales Price: $22550.8
Car Information:
Model Name: 2022 Nissan Altima
Top Speed: 130 miles per hour
Sales Price: $24900.5
Car Information:
Model Name: NoName
Top Speed: -1 miles per hour
Sales Price: $0
0-60mph Acceleration: 0
It works fine, but I want the last output "0-60mph Acceleration" to read -2 instead of 0. I just don't know how to declare a default constructor for the subclass to do that.
Do you mean:
class SportsCar : public Car {
public:
SportsCar()
: Car() // Parent Init
// Preferrer using initializer list for members
// After Parents come members
, acceleration(-2)
{}
....
};

how do i initialize 2 static members belonging to 2 different derived classes

New to c++. I'm solving questions to understand better.
So, i have to make a program which has a parent class called Person and it has 2 derived classes named Student and Professor. The parent class Person has normal variables - std::string name and int age. The derived class Student has variables int sum, int marks[6] and static int cur_id. The derived class Professor has variables int publications and static int cur_id.
Now both the derived classes have 2 overloaded methods, getdata() - gets input from user and putdata() - prints data.
Also both have a static variable named cur_id which gets incremented when an object gets constructed.
Now the problem comes when i try to initialize the static variables using the below code -
int Student::cur_id;
int Professor::cur_id;
I get the following error -
'int Professor::cur_id': redeclaration of member is not allowed.
here is the full code -
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
class Person
{
protected:
std::string name;
int age;
public:
Person()
:age(0)
{}
};
class Professor : public Person
{
private:
int publications;
static int cur_id;
public:
Professor() //constructor
:Person(), publications()
{
++cur_id;
}
void getdata()
{
std::cin >> name >> age >> publications;
}
void putdata()
{
std::cout << name << " " << age << " " << publications << " " << cur_id << std::endl;
}
};
class Student : public Person
{
private:
int marks[6];
static int cur_id;
int sum;
public:
Student() //constructor
:marks{ 0 }, sum(0), Person()
{
++cur_id;
}
void getdata()
{
std::cin >> name >> age;
for (int index{}; index < 6; ++index)
{
std::cin >> marks[index];
sum += marks[index];
}
}
void putdata()
{
std::cout << name << " " << age << " " << sum << " " << cur_id;
}
};
int Student::cur_id;
int Professor::cur_id;
int main()
{
Student student;
student.getdata();
student.putdata();
Student nobita;
nobita.getdata();
nobita.putdata();
return 0;
}
Any help is appreciated, thanks
You should define cur_id in Professor class as static.

derived class giving error when accessing private variables of base class

I am making a c++ program to store employee's data like name, id, saleamount, commission amount and calculate earning (sales*commission). I am using the concept of inheritance. My base class is 'Employee' and my derived class is 'SeniorEmployee'. When I run the program, the compiler gives me an error that I cannot access the private members of base class. The errors are like this
error: 'std::__cxx11::string Employee::name' is private.
Another error on 2nd line is
error: 'int Employee::id' is private
Again the same error on 3rd line
error: 'double Employee::sales' is private
Following is my code. I have included all files.
File Employee.h
#ifndef EMPLOYEE_H_
#define EMPLOYEE_H_
#include <iostream>
#include <string>
using namespace std;
class Employee {
public:
Employee(string EmpName, int EmpID, double EmpSales, double EmpComm);
void setName(string EmpName);
string getName();
void setID(int EmpID);
int getID();
void setSales(double EmpSales);
double getSales();
void setComm(double EmpComm);
double getComm();
double earning();
private:
string name;
int id;
double sales;
double commission;
};
#endif
File Employee.cpp
#include <iostream>
#include <string>
#include "Employee.h"
using namespace std;
Employee::Employee(string EmpName, int EmpID, double EmpSales, double EmpComm): name(EmpName), id(EmpID), sales(EmpSales), commission(EmpComm)
{
}
void Employee::setName(string EmpName) {
name=EmpName;
}
string Employee::getName() {
return name;
}
void Employee::setID(int EmpID) {
id=EmpID;
}
int Employee::getID() {
return id;
}
void Employee::setSales(double EmpSales) {
sales=EmpSales;
}
double Employee::getSales() {
return sales;
}
void Employee::setComm(double EmpComm) {
commission=EmpComm;
}
double Employee::getComm() {
return commission;
}
double Employee::earning() {
return sales*commission;
}
File SeniorEmployee.h
#ifndef SENIOREMPLOYEE_H_
#define SENIOREMPLOYEE_H_
#include "Employee.h"
#include <iostream>
#include <string>
using namespace std;
class SeniorEmployee: public Employee {
public:
SeniorEmployee(string EmpName, int EmpID, double EmpSales, double EmpComm, double BaseSalary);
void setBaseSalary(double BaseSalary);
double getBaseSalary();
private:
double bsalary;
};
#endif
File SeniorEmployee.cpp
#include <iostream>
#include <string>
#include "SeniorEmployee.h"
using namespace std;
SeniorEmployee::SeniorEmployee(string EmpName, int EmpID, double EmpSales, double EmpComm, double BaseSalary) : Employee(name,id,sales,commission)
{
}
void SeniorEmployee::setBaseSalary(double BaseSalary) {
bsalary=BaseSalary;
}
double SeniorEmployee::getBaseSalary() {
return bsalary;
}
File main.cpp
#include <iostream>
#include "SeniorEmployee.h"
using namespace std;
int main() {
string empname = "Fareed Shuja";
int empid = 3978;
double empsales = 30.0;
double empcomm = 0.99;
double basesalary = 50.0;
SeniorEmployee emp(empname,empid,empsales,empcomm,basesalary);
cout << "Name of the Employee is : " << emp.getName() << endl;
cout << "Employee ID is : " << emp.getID() << endl;
cout << "Sale Amount is : " << emp.getSales() << endl;
cout << "Commission is : " << emp.getComm() << endl;
cout << "Earning is : " << emp.earning() << endl;
cout << "Employee's base salary is " << emp.getBaseSalary() << endl;
return 0;
}
The following line in SeniorEmployee.cpp is incorrect:
SeniorEmployee::SeniorEmployee(string EmpName, int EmpID, double EmpSales, double EmpComm, double BaseSalary) : Employee(name,id,sales,commission)
It's attempting to access the private variables 'name', 'id', etc... instead of passing your constructor's arguments to the base class constructor. It should instead be:
SeniorEmployee::SeniorEmployee(string EmpName, int EmpID, double EmpSales, double EmpComm, double BaseSalary) : Employee(EmpName,EmpID,EmpSales,EmpComm)
Also if you want to access variables from a derived class but not make them visible outside of the class they must be declared protected instead of private.

C++: How to get a private property with a dynamic variable in a class?

I would like to create a simple Car class that has a Car::get method that I can use to access private properties of the car with a string such as:
// Create Car Intance
Car myCar;
cout << myCar.get("wheels");
My problem is that I don't know how to point the private property with a dynamic variable. Here is the class:
// Libraries & Config
#include <iostream>
using namespace std;
// Create Car Class
class Car {
private:
int wheels = 4;
int doors = 5;
public:
Car(); // constructor
~Car(); // deconstructor
int get(string what); //
};
// Constructor
Car::Car(){ cout << "Car constructed." << endl; }
// Deconstructor
Car::~Car(){ cout << "Car deconstructed." << endl; }
// Get Method
int Car::get(string what){
// === THE PROBLEM ===
// How do I access the `wheels` property of the car class with the what argument?
return this[what] // ??
}
// Create Car Instance
Car myCar;
cout << myCar.get("wheels");
You can do something like this using a std::map:
#include <map>
#include <string>
#include <iostream>
using namespace std;
class Car {
private:
std::map<std::string, int> parts = {{"wheels", 4}, {"doors", 5}};
public:
Car();
~Car();
int get(std::string what);
};
// Constructor
Car::Car(){ std::cout << "Car constructed." << endl; }
// Deconstructor
Car::~Car(){ std::cout << "Car deconstructed." << endl; }
// Get Method
int Car::get(string what){
return parts[what];
}
int main()
{
// Create Car Intance
Car myCar;
cout << myCar.get("wheels") << '\n';
}
It is worth reading up on exactly how a std::map works here: http://en.cppreference.com/w/cpp/container/map
class Car {
private:
int wheels = 4; <<< This would flag an error as you cannot provide
int doors = 5; <<< in class initialization for non-consts.
int Car::get (string what)
{
if( what == "wheels" ) //// check for case sensitivity...
return wheels;
else
return doors;
}