Dynamically creating two objects and assigning one to the other [duplicate] - c++

The goal of my program is to allow the user to enter up to 100 names for people and 100 names for cars. Then the user can "register" a car to as many people as s/he wishes using pointers. I know I need a person class and a car class and I need to use two arrays of size 100 for each. But I am completely lost on how to set anything else up. I have done a lot of researching to try and figure something out. I would be extremely appreciative if anyone could give me some basic example code for how something like this could be done.
I don't have much code:
class Person{
public:
person();
Car* in_car;
};
class Car{
public:
Car();
};
int main()
{
Car cars[101];
Person people[101];
}

You could add a vector of car pointers to the People class.
class People{
...
private:
vector<Car*> _pointer;
};

Related

Public inheritance for all except one function

Say I have the following classes:
class Car
{
...
public:
void drive(Direction direction);
void open_door();
void refuel();
double get_speed();
...
};
class SelfDrivingCar: public Car
{
CarDrivingProgram *driving_program;
...
};
class CarDrivingProgram
{
public:
virtual void drive_car(Car *car) = 0;
};
class ExampleCarDrivingProgram: public CarDrivingProgram
{
void drive_car(Car *car) override;
...
};
SelfDrivingCar is a Car in every way except the user is forbidden from manually driving it. Instead, CarDrivingProgram drives it via drive_car(...). Using public inheritance seems correct because most operations on a Car could also happen to a SelfDrivingCar. For example, the user might create an array of Cars and then refuel all the Cars in the array, some of which happen to be SelfDrivingCars.
However, using public inheritance exposes the drive(...) method, which the user should not call on a SelfDrivingCar.
One solution would be to make the drive(...) method private in SelfDrivingCar, but that's messy, requires all CarDrivingPrograms to be friends in order to access drive(...), and can be circumvented if the user casts a SelfDrivingCar to a Car and then calls drive(...) from the Car.
Another solution would be to keep a boolean flag that indicates whether a Car is currently allowed to be driven or not and printing an error if drive(...) is called when the flag is set to "false". For a SelfDrivingCar, this flag would be "false" for most of the time, and CarDrivingProgram would temporarily set this to "true" for the duration of drive_car(...). However, this catches mistakes at runtime rather than at compile time, and the user can still toggle the flag and drive a SelfDrivingCar manually if they really want to.
Using protected/private inheritance would be another solution, but that prevents the user from doing something like adding SelfDrivingCars to an array of Cars that are to be later refuelled (described earlier).
How do I cleanly forbid the user from calling drive() on a SelfDrivingCar, ideally catching things at compile thing?
For clarification: The SelfDrivingCar class still needs a drive(...) function or something like it because CarDrivingProgram needs a way to tell SelfDrivingCar the direction to drive in. CarDrivingPrograms can drive any Car, not just SelfDrivingCars. I want CarDrivingProgram to be able to drive SelfDrivingCars but for the user to be unable to. For example, the user could have an array of pairs of CarDrivingPrograms and Cars, and call carDrivingProgram[i]->drive_car(car[i]) for each pair. I could make all CarDrivingPrograms friends but that's messy.
You could do something like this:
class Car {
...
public:
void open_door();
void refuel();
double get_speed();
...
};
class NormalCar: public Car{
public:
void drive(Direction direction);
};
class SelfDrivingCar: public Car
{
CarDrivingProgram *driving_program;
...
};
This is a very clean way. When there are no reasons you can't introduce another class, this should be fine. You can still store them in an array and refuel them.
When SelfDrivingCar is a Car that can drive, you can make it a Car and call the function (like TheUndeadFish mentioned in his comment). But you can't make a SelfDrivingCar a NormalCar.

Stack array of structures

I'm trying to figure our how implement an array of structures into stacks in this machine problem that i have. Here is the problem:
Make a program that will allow the user to perform the following activities stated below through array approach. Car Park Station offers 10 park lanes and each lanes can accommodate 5 cars.
a. Entry. It must be able to register new car and assign an available parking lane. Registration requires plate number, brand name, car color, owner and telephone number.
b. Release. It must be able to release car from an identified lane
c. Search. It must be able to identify the car location based on plate number.
d. Vacancy. It must be able to display available parking space.
From what i understand, i have to make a 2 dimensional array of structures containing various data types and i have to make a lifo code out of it. But my problem is, i know how to simulate an array approach lifo code with just a single data type but not with multiple data types. The part where i have to implement the 2 dimensional array of structure into a stack is where i got me stuck and confused. I've searched online to look for problems similar to mine but i couldn't find any. I tried to make a code shown below:
struct Car
{
string brand, color, owner;
int plate, phone;
};
class Stack
{
private:
Car * pointer = new Car[10][5];
int top;
public:
Stack() // Constructor
{...}
void Push(int plate, string brand, string color, string color, string owner, int number)
{...}
Pop()
{...}
}
Try to analyze your problem further before choosing an actual implementation solution (like 2-dim array).
In your task you have the following abstract entities:
CarParkStation with attributes: NumberOfParkLanes, which should be able to do something like: FindFreeLane, FindCar(plateNum), RegisterACar(car), ReleaseACar(car)
Lane with attributes: NumberOfPlaces, and with actions like: IsFull(), and maybe also: FindACar(plateNum), AddACar(car), RemoveACar(car)
Car with attributes: PlateNumber, Brand, Color, Owner, which should be able to do: GetPlateNumber(), and maybe also provide access to other parameters
Below is a very general example of possible CarParkStation class declaration:
class CarParkStation
{
public:
CarParkStation() = delete;
explicit CarParkStation(int numParkLanes);
~CarParkStation() = default;
std::shared_ptr<const Lane> FindFreeLane();
std::shared_ptr<const Car> FindCar(const PlateNumber& pNumber);
std::pair<std::shared_ptr<const Lane>, int position> FindWhereMyCarIsParked(const PlateNumber& pNumber);
bool RegisterACar(const Car& car);
bool ReleaseACar(const Car& car);
private:
std::vector<std::shared_ptr<const Lane> > lanes_;
std::set<std::shared_ptr<Car>, CustomCompareFunction > cars_;
};
Don't forget to write the tests along with your implementation. This will help you to verify your requirements and overall design. For example:
TEST_F(CarParkStationShould, returnCorrectFreeLane)
{
ASSERT_EQ(expectedFreeLane, carParkStation->FindFreeLane());
}
In general, focus on what should your application do first, and then think about how to implement it.

c++ array with multiple objects

So I am creating a simple game map initialized as follows:
char map[MAP_SIZE][MAP_SIZE];
Now, as you can see, right now it is of just char. The problem is, I want the map to hold different types of objects instead. This is what I did so far but I wanted to see if there was a more efficient way(which there probably is).
class Treasure{};
class Chest{};
class Enemy{};
class Grunt : public Enemy{};
class Lieutenant : public Enemy{};
class Boss : public Enemy{};
class Final_Boss : public Enemy{};
class Secret_Room{};
class Map_Level{};
struct Entity
{
char display_char; //Simple character that is displayed on the the map
Treasure *t;
Chest *c;
Grunt *g;
Lieutenant *l;
Boss *b;
Final_Boss *f;
Secret_Room *s;
Map_Level *u;
Map_Level *d;
};
Entity map[MAP_SIZE][MAP_SIZE];
I thought about just checking the display_char and depending on what it is, just deleting the object pointers I don't need but that seems like a lot of unnecessary work. I hope this question is clear enough and would appreciate any help figuring out the best way to do this.
Assuming you only want one enemy per map entry, you could just have a Enemy * instead of having the whole list of Grunt, Lieutenant, etc.

Interaction between objects

If I have a class Music like this
class Music{
private:
string song[20];
string album[20];
string artistName[20];
string genre[20];
static int i;
int j;
int duration[20];
public:
Music(string musicName,string artist,string genre,string albumname,int duration);
void addMusic(string musicName,string artist,string genre,string albumname,int duration);
bool browseMusic(string musicName);
void getParticularSongDetail(string musicName);
void totalNumberOfSongs();
};
and a person class like this
class Person{
public:
Person(string,string,string);
string getFirstName();
string getMiddleName();
string getLastName();
int getId();
private:
//some variables
}
how can I add 20 songs to Music class that belongs to a particular person?
The answer really depends on how you wish to design your program.
The following are some possible solutions for you:
The Person could have an array of Music objects.
The Music class could have a keep track of the Peron's id it belongs to.
The Music classes may be something you won't want to repeat between users, so you might make a 3rd class which helps make the associations. (e.g. Multiple people might own the same Tool album CD/mp3, so another class could help you make the associations, or you might have an array in your Music class to keep track of multiple Persons... Normally a "list" would be a better datatype than an array, however from your code examples I stuck to arrays to keep the response simple).

C++ How to create subclass in class with array [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
C++ How to create subclass in class with array
Hi guys, i still learning C++ and face some issues here.
Basically i got a parent class
lets call this parent class as
Vehicle
It got 2 sub class, lets assume they are
Car and Motorcycle
I will create a vehicle object assume vehicle size is 20
Vehicle veh[20]
I will do the following
string vType;
cout << "Please enter your vehicle Type:";
cin >> vType;
so i do a comparision if (vType=="Car")
it will return 4 wheels from the sub class, but how do i declare its 4 wheels at Car and 2 wheels at Motorcycle , i know i need create 2 additional cpp file which is
class Car : public Vehicle
{
private:
int noOfWheels;
public:
computePrice();
}
But how do i set noOfWheels specially to Car as 4 and Motorcycle as 2.
The next is the tricky part.. after knowing how many wheel it is
i will need store a array for each wheel
string wheel[4];
since i know there 4 wheel in cars.
How do i prompt 4 type and store it in an array, and all of this in an object call Vehicle.
I can use a for loop and thats not the issue, the part i am stuck on is how do i create a string array and store the 4 prompt and then into this Vehicle[0]
wheel 1:
wheel 2:
wheel 3:
wheel 4:
When user want to print data it will be
Vehicle[0]
Type: Car
Wheel: 4
Wheel[0] = Fine condition
Wheel[1] = Need to check again
Wheel[2] = Fine condition
Wheel[3] = Might need get repair
Thanks for all help.
Firstly the declaration for your array is wrong. Since you are dealing with polymorphic classes you need to use pointers.
Vehicle* veh[20];
Otherwise you will have what is called object slicing. Which means that even if you create a Car or a Motorcycle they will be converted into Vehicles when you assign them to your array.
'how do i set noOfWheels specially to Car as 4 and Motorcycle as 2.'
In the constructor
class Car : public Vehicle
{
public:
Car() : noOfWheels(4) { ... }
private:
int noOfWheels;
...
};
class Motorcycle : public Vehicle
{
public:
Motorcycle() : noOfWheels(2) { ... }
private:
int noOfWheels;
...
};
But personally I don't think you need a noOfWheels data member at all. Since the number of wheels is fixed for each type of Vehicle it's a waste of space, instead you need a virtual function
class Vehicle
{
public:
virtual int noOfWheels() const = 0;
...
};
class Car : public Vehicle
{
public:
virtual int noOfWheels() const { return 4; }
...
};
class Motorcycle : public Vehicle
{
public:
virtual int noOfWheels() const { return 2; }
...
};
'how do i create a string array and store the 4 prompt and then into this Vehicle[0]'
Again I would use the constructor to initialize the car wheel names.
class Car : public Vehicle
{
public:
Car(const std::string* w)
{ wheel[0] = w[0]; wheel[1] = w[1]; wheel[2] = w[2]; wheel[3] = w[3]; }
virtual int noOfWheels() const { return 4; }
private:
std::string wheel[4];
...
};
Use constructors to initialize classes. That's what they are for.
Looks like the answer has been accepted, but I typed it all so I will post it all. It's a run down of OOP I guess.
Lets assume that all vehicles have wheels. All those wheels have a condition. Some vehicle have more or less wheels than others.
You need to separate the common aspects of the classes into higher orders, into base classes.
You also need to organize your classes to compose themselves with other classes to build a whole.
Here we have a wheel class, it has a condition, which is a string. You can query it's condition at any time.
class Wheel
{
public:
const std::string GetCondition() const { return mCondition; }
private:
std::string mCondition;
};
We know that a vehicle is going to have wheels, so we store the wheels container here, to share out among the child classes through inheritance.
class Vehicle
{
public:
Vehicle(unsigned int wheelCount) { mWheels.resize(wheelCount, Wheel()); }
virtual unsigned int GetWheelCount() { return mWheels.size(); }
virtual const std::string GetWheelCondition(int wheelNumber)
{
return mWheels[wheelNumber].GetCondition();
}
protected:
std::vector<Wheel> mWheels; // All vehicles have wheels.
};
A car is a type of Vehicle. Therefore it inherits from Vehicle. It has inherited a member that holds Wheel objects. It has also inherited methods that help to find the wheel count and to get the status of a wheel by index. This is the level that you can specialize you classes. The Car and Motorbike class both have wheels, and they have the same core functionality. We can specialize the class by adding or overloading a method.
class Car : public Vehicle
{
public:
Car() Vehicle(4) {}
Car(unsigned int wheelCount) : Vehicle(wheelCount) {}
}
class Motorbike : public Vehicle
{
public:
MotorBike(unsigned int wheelCount) : Vehicle(wheelCount) {}
void DoWheelie() { throw; }
}
We can use these object like so,
Car car(4); // Car with 4 wheels. specialized constructor.
Car standardCar(); // Car with 4 wheels, as default constructor.
Car uberCar(42); // Car with 42 wheels.
Motorbike bike(2); // Bike with 2 wheels.
Motorbike badBike(); // No default constructor defined! Will not compile!
car.GetWheelCount(); // 4
bike.GetWheelCount(); // 2
bike.DoWheelie(); // All good.
car.DoWheelie(); // NOPE! Method doesn't exist for this.
There is more to say on the benefits of polymorphism and heap allocation, but I think I'll leave it here. Hope it's helpful.