Setting value using base class functions from derived class - c++

I'm new to c++. I'm trying to complete a c++ assignment involving Inheritance where the Car class must contain these methods setGarageSpaces function to set garage space to 2, and setNumWheels function to set wheels to 4.
I'm creating a no parameter constructor and inheriting from the base class Vehicle then using the set functions but I'm getting an error.
#include <iostream>
using namespace std;
class Vehicle
{
public:
Vehicle();
void setGarageSpaces(size_t spaces)
{
garage_spaces_ = spaces;
}
void setNumWheels(size_t wheels)
{
num_wheels_ = wheels;
}
Vehicle(std::string name, std::string manufacturer, double top_speed, double weight, double mpg, double curr_gas_amt);
protected:
size_t garage_spaces_; // number of garage slots this vehicle takes up
size_t num_wheels_;
};
class Car : public Vehicle { //Car derived class inherits from base class Vehicle
public:
Car(){ //no para constructor
setGarageSpaces(2);
setNumWheels(4);
}
Car(std::string name, std::string manufacturer, double top_speed, double weight, double mpg);
};
int main() {
Car c;
}

public:
Vehicle();
Default Constructor for Vehicle is not implemented, you may want to do :
public:
Vehicle() {}
When you expect proper construction, you can remove the default constructor from class, forcing user to impl. the proper constructor call.

Related

C++ How to instantiate abstract parent class constructor from child class

I have an abstract class, that has two variables. I want to instantiate those variables through the constructor.
Then I want to instantiate those variables from the child classes constructors, but it giving me a casting error?
#ifndef Employee_Interface_H
#define Employee_Interface_H
#include <iostream>
using namespace std;
class Employee {
private:
double salary = 0;
double sales = 0;
double bonus = 0;
public:
Employee(double empSalary, double empSales) {
salary = empSalary;
sales = empSales;
}
void virtual calculateBonus() = 0;
};
class Staff : public Employee {
public:
Staff(double empSalary, double empSales) {
Employee(empSalary,empSales);
}
void calculateBonus() {
//20% of salary
}
};
#endif
`
Instead of this:
Staff(double empSalary, double empSales) {
Employee(empSalary,empSales);
}
Use this instead:
Staff(double empSalary, double empSales) :
Employee(empSalary, empSales)
{
}
You have to put the base class constructor call in the derived class constructor's member-initialization-list - after the : marker, but before the constructor's body definition.

C++ Inheritance accessing a non-virtual function in derived class from base class pointer

Consider the following code for
class BankAccount
{
protected:
int accNo;
int balance;
std::string custName;
std::string custAddress;
public:
BankAccount(int aNo, int bal, std::string name, std::string address);//:accNo(aNo), balance(bal), custName(name), custAddress(address);
BankAccount(const BankAccount&);
BankAccount();
~BankAccount();
BankAccount& operator=(const BankAccount&);
int getAccNumber() const {return accNo;};
virtual int getBalance() const {return balance;};
std::string getAccountHolderName()const {return custName;};
std::string getAccountHolderAddress()const {return custAddress;};
virtual std::string getAccountType()const{return "UNKNOWN";};
};
class CurrentAccount:public BankAccount
{
private:
int dailyTrancLimit;
public:
CurrentAccount(int aNo, int bal, std::string name, std::string address);
int getTransactionLimit()const {return dailyTrancLimit;};
void setTranscationLimit(int transLimit){dailyTrancLimit = transLimit;};
std::string getAccountType()const{return "CURRENT";};
};
class SavingAccount:public BankAccount
{
private:
int intrestRate;
int accumuatedIntrest;
public:
SavingAccount(int aNo, int bal, std::string name, std::string address);
int getBalance()const {return balance+accumuatedIntrest;};
void setIntrestEarned(int intrest){accumuatedIntrest=intrest;};
std::string getAccountType()const{return "SAVINGS";};
};
I want to call setIntrestEarned() in SavingAccount class with base class pointer. I don't want to add setIntrestEarned() as virtual in base class BankAccount because it has no meaning in the other type of accounts like derived one CurrentAccount.
And if we keep adding various function in different derived class as virtual in base class then it will end up like a superset of functions of derived class.
What would be the best way to design these type of class hierarchy?
If it has no meaning in your base class, then you do not need to inherit from it.
Inheritance is only useful in the form where:
B is a subset of A.
B can have exclusive functions that A does not have.
Hence, if your savingsacc class requires certain information that A contains, then inherit it, and create exclusive functions for B that A does not need as C may also be a subset of A.

Can a derived class have a constructor that is not in the base class in C++?

Say I have a base class:
class Animal
{
public:
Animal(double length, double height);
virtual ~Animal();
private:
fLength;
fHeight;
};
The constructor sets fLength = length and fHeight = height.
I have a derived class Fish which works fine.
But say I have a derived class Cat which has another property fLegs which needs to be set in the constructor. A fish does not have legs so it does not make sense for the Animal base class to have the property fLegs.
Can a constructor for Cat be created like:
Cat(double length, double height, double Legs) ?
I have tried this but an error comes up saying there is no matching function call to Animal.
Is there any way I can get around this without making the Fish have an fLegs property and setting it to 0 for the Fish?
Yes.
Example:
class Animal
{
public:
Animal(double length, double height) : fLength(length), fHeight(height) {}
virtual ~Animal(){};
private:
double fLength;
double fHeight;
};
class Cat : public Animal
{
public:
Cat(double length, double height, double Legs) : Animal(length, height), fLegs(Legs) {}
private:
double fLegs;
};
int main(void)
{
Cat(1,2,4);
return 0;
}
You can use the code below. First initialize the base class constructor. Then derived class variables.
class Cat : public Animal
{
public:
Cat(double length, double height, double legs) : Animal(length, height), fLength(legs)
{
}
private:
double flegs;
};

How to define the constructor in a child class

I am having difficulty trying to implement a constructor for my child class. I understand the purpose of the constructor is to set the states of the class to the values passed? am I correct in this?
I am getting an error;
no matching function for call to 'superclass'
My question is do I have to link my constructor for a child class to the superclass? what is the relationship in terms of constructors between the two classes?
#include<iostream>
using namespace std;
class Buildings
{
private:
float price, area;
string city;
public:
Buildings(float, float, string);
// Buildings(float, float, float);
void virtual display();
void virtual getprice(float);
void virtual getcity(string);
void virtual getarea(float);
};
Buildings::Buildings(float b_price, float b_area, string b_city):price(b_price), area(b_area), city(b_city)
{
}
void Buildings::display()
{
cout<<"The city, price and area(sqft) of the building are: "<<city<<endl<<price<<endl<<area;
}
void Buildings::getprice(float aprice)
{
price = aprice;//potential error handling
}
void Buildings::getarea(float asize)
{
area = asize;
}
void Buildings::getcity(string acity)
{
city = acity;
}
class Apartment:public Buildings
{
private:
float numtennants;
float rent;
float rentpr;
public:
Apartment(float numres, float numrent, float numrentpr);
void virtual display();
void virtual avgrent(float);
void virtual totrent(float);
void virtual totres(float);
};
Apartment::Apartment(float numres, float numrent, float numrentpr):numtennants(numres),rent(numrent),rentpr(numrentpr)
{}
void Apartment::display()
{
Buildings::display();
}
Buildings doesn't have a default constructor. You must explicitly call the only Buildings constructor that exists, passing along the suitable arguments.
If you want do disallow public default-construction of Buildings objects, but allow child-classes to use it, you can make a default constructor that is protected. Like
class Buildings
{
public:
// Public constructor, only way to construct object of this class
// for the general public
Buildings(float, float, string);
// Other public functions...
protected:
// Default constructor, which initializes the private members
// to some suitable values
// Only usable by child-classes
Buildings()
: price(0), area(0), city("")
{}
private:
float price, area;
string city;
};
You must call the parent class's constructor in your child class's member initializer list.
struct A {
A(int a) : a_(a) {}
int a_;
};
struct B : public A {
B(int a, int b) : A(a), b_(b) {}
int b_;
};

Set class name inherit and display in another class

Why am I not able to set the class name and inherit it and display in another class like the code given below? What am I doing wrong?
#include<iostream>
#include<string>
using namespace std;
class dealer
{
string name;
public:
dealer(){};
dealer(string n): name(n){};
~dealer(){};
//void setname(string n){name = n;};
void display(){cout<<name<<endl;}
};
class car : public dealer
{
public:
dealer b;
car(){};
//car(string n): dealer(n){};
~car(){};
void display(){dealer::display();}
};
int main ()
{
dealer a("ABC");
car c;
c.display();
}
It is working properly. You initialize c with the car default constructor which implicitly call the dealer default constructor which doesn't do anything. name remains an empty string, which is what is printed out. To solve this problem:
//car(string n): dealer(n){}; <--- uncomment
car c("ABC"); //initialize like this
From comment: Your inheritance hierarchy is incorrect. car has-a dealer, but isn't a dealer. A better design system would look like this:
class dealer { ... };
class car
{
dealer &d;
car(dealer &nd): d(nd) { };
void display(){ d.display();}
}