Inheritance and Polymorphism

I am working on a project that require us to use inheritance and polymorphism. The program is not complete, this is what I have got so far, but I am not sure what I am doing wrong.
I'm getting this error. Line 10:int Vehicle::year' is private.
Please help me.


#include <stdio.h>
#include <string.h>
#include <iostream>

class Vehicle
{
private:
char* license;
double fee;
int year;
Vehicle(char* l, int y);
virtual void print();
void setFee(double f);
double getFee() {return fee;};
int getYear() {return year;};
char* getlicense() {return license;}
};

char* dupstr(char *s) // a function for duplicating a string
{
return strcpy(new char[strlen(s)+1],s);
}

Vehicle::Vehicle(char* l, int y)
{
license = dupstr(l);
year = y;
fee = 0;
}

void Vehicle::print()
{
printf("Vehicle: %s %d\n", license, year);
if(fee!=0) printf(" Fee: $%5.2f\n", fee);
}

void Vehicle::setFee(double f)
{
fee = f;
}

class Car: public Vehicle {
private:
char *style;
int weight;

public:
Car(char* l, int y, char* s);
void setWeight(int w);
void print();
};

class Truck: public Vehicle {
private:
int wheels;
int grossWeight;

public:
Truck(char* l, int y, int w);
void setWeight(int w);
void print();
};

Car::Car(char* l, int y, char* s): Vehicle(l, y)
{
style = dupstr(s);
}
void Car::setWeight(int w)
{
weight = w;
if(w<3000) setFee(30);
else if(w<5000) setFee(40);
else setFee(50);
}
void Car::print()
{
printf("Car: %s %d\n", getlicense(), year, style);
if(fee!=0) printf(" Fee: $%5.2f\n", fee);


}
Truck::Truck(char* l, int y, int w): Vehicle(l, y)
{
wheels = w;
}
void Truck::setWeight(int w)
{
grossWeight = w;
if(grossWeight<3000) setFee(30);
else if(grossWeight<5000) setFee(40);
else if(grossWeight>10000) setFee(50);
else if (grossWeight>20000) setFee(60);
else setFee(70);
}

void Truck::print()
{
printf("Truck: %s %d\n", getlicense(), getyear(), wheels);
if(fee!=0) printf(" Fee: $%5.2f\n", fee);
}
int main()
You did not put [code] [/code] tags around your code.
You did not include the main() function.

That said, you cannot access something that is private in the subclass (Car and Truck).
If you want to inherit something that should not be accessible outside, use protected instead of private in Vehicle.
I am sorry for not putting the tags around my code. Thank you catfish it does work with protected. I am having another problem, when I run the program, the style of the car and the wheels of the truck are not printing, is there anything wrong in my void print?
Last edited on
protected is not the same as public, if that's what you're afraid of.

But no, whatever is private in a superclass, cannot be accessed when that class is inherited by a subclass.
I got it thank you.
Topic archived. No new replies allowed.