I am new in c recently i started learning poo I want to create a class movies and a class.
directors a class movie should have an array of directors and I want to fill that array from the console. When I run the code it show me the first and second line and stop executing :
enter image description here
this is my code:
#include<iostream>
#include<string>
using namespace std;
class directors{
string name;
string lastname;
public:
directors(){
}
directors(string a,string b){
name=a;
lastname=b;
}
void createdirector(){
cout<<"name of director:"<<endl;
cin>>name;
cout<<"last name:"<<endl;
cin>>lastname;
}
};
class movie{
string name;
directors* director;
public:
film(){
directors* director=new directors[20];
};
void creatmovie(){
cout<<"name of movie"<<endl;
cin>>name;
director[0].createdirector();
}
};
int main(){
movie a;
a.creatmovie();
}
CodePudding user response:
A better way wold be to use std::vector as shown below. The advantage of using a std::vector is that you don't have to worry about manual memory management(like using new and delete explicitly). vector will take care of it(memory management). You can use the below given example as a reference.
#include<iostream>
#include<string>
#include <vector>
class director{
std::string name;
std::string lastname;
public:
director(){
}
//use constructor initializer list
director(std::string a,std::string b): name(a), lastname(b){
}
void createDirector()
{
std::cout<<"Enter name of director:"<<std::endl;
std::cin>>name;
std::cout<<"Enter last name:"<<std::endl;
std::cin>>lastname;
}
void displayDirector() const
{
std::cout << "Firstname: "<<name<<" Lastname: "<<lastname<<std::endl;
}
};
class movie{
std::string name;
std::vector<director> directors; //vector of director objects
public:
//constructor that creates vector directors of size vecSize
movie(size_t vecSize): directors(vecSize)
{
std::cout << "Enter name of movie: "<<std::endl;
std::cin >> name;
//iterate through the vector and call method createDirector on each element
for(director &elem: directors)
{
elem.createDirector();
}
}
void displayMovie()
{
std::cout<<"Movie's name is: "<<name<<std::endl;
//iterate through the vector and call displayDirector on each object
for(const director& elem: directors)
{
elem.displayDirector();
}
}
};
int main(){
movie a(4); //create an object of type movie. Note i have passed 4 as argument you can pass other numbers like 3,2 etc
a.displayMovie();//display movie info
}
Some of the modifications that i made are:
- Used constructor initializer list in class
director - added a method called
displayDirectorin classdirector - added a method called
displayMoveiin classmovie - added a data member called
directorsthat is astd::vector<director>in classmovie. - added a constructor for class
moviethat initializes the data memberdirectors. - removed unnecessary method named
filmfrom classmovie - not used
using namespace std;which is a recommended practice
The output of the above program can be seen here.
