Can someone please help me with the below requirement
Class book that that contains attributes BookId, BookName, and Price. It also contain member function to input and show its attributes.
Write another class Writer that contains that contains the attributes of WriterName, Address and NumberofBooks written by him. It contains array of book objects as iys member. The length of array should be 5 to store the data of five books.
It should also contain a member function to input and display its attributes.
I found a solution on google with below code but it appears it is useful for my half requirement.
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
class BOOK
{
int BOOKNO;
char BOOKTITLE[20];
float PRICE;
void TOTAL_COST(int N)
{
float tcost;
tcost=PRICE*N;
cout<<tcost;
}
public:
void INPUT()
{
cout<<"Enter Book Number ";
cin>>BOOKNO;
cout<<"Enter Book Title ";
gets(BOOKTITLE);
cout<<"Enter price per copy ";
cin>>PRICE;
}
void PURCHASE()
{
int n;
cout<<"Enter number of copies to purchase ";
cin>>n;
cout<<"Total cost is ";
TOTAL_COST(n);
}
};
void main()
{
BOOK obj;
obj.INPUT();
obj.PURCHASE();
getch();
}
To contain an instance of an object you declare a member of that type in your class:
class Writer
{
const size_t MAX_BOOKS_WRITTEN = 5U;
Book books_written[MAX_BOOKS_WRITTEN];
};
In the above class, "that contains that contains" an array of books written.
Related
Is there any method that I can call display function of Purchase class.
#include <iostream>
#include<stdio.h>
#include<string>
using namespace std;
class Purchase
{
private:
string userName;
int countOfItems;
float amount;
float static totalAmt;
int static totalCountOfItems;
public:
void display(Purchase obj[],int n)
{
for(int i=0;i<n;i++)
{
setTotalAmt(obj[i].getTotalAmt()+obj[i].getAmount());
setCountOfItems(obj[i].getCountOfItems()+obj[i].getCountOfItems());
}
cout<<"Total Amount Received :"<<getTotalAmount();
cout<<"Total Number of Items sold :"<<getTotalCountOfItems();
}
};
getters and setter are already member functions.
How can i call display function in main function
My main function looks like this:
#include <iostream>
#include<string>
#include<stdio.h>
#include "Purchase.cpp"
using namespace std;
int main()
{
int n;
string userName;
int countOfItems;
float amount;
cout<<"Enter the Number of customers :";
cin>>n;
Purchase P[n];
for(int i=0;i<n;i++)
{
cin.ignore();
cout<<"Enter the Name of the customer :";
getline(cin,userName);
P[i].setUserName(userName);
cout<<"Enter the No of Items purchased :";
cin>>countOfItems;
P[i].setCountOfItems(countOfItems);
cout<<"Enter the purchase amount :";
cin>>amount;
P[i].setAmount(amount);
}
cout<<"Purchase Details :";
for(int i=0;i<n;i++)
{
cout<<"Customer "<<i+1<<" :"<<P[i].getUserName()<<endl;
cout<<"No of Items purchased :"<<P[i].getCountOfItems()<<endl;
cout<<"Purchase amount :"<<P[i].getAmount()<<endl;
}
cout<<"\n";
return 0;
}
At last i have to add calling of display function so that i can add amount and countofitems of every object.
Is there any method to call class member functions?
You could take the address of a member function and pass that later.
But with C++11 or better (read n3337, the C++11 standard), please read more about C++ then consider using lambda-expressions. Of course use <algorithm> and <functional> standard headers.
Take also time to read more about standard containers and strings.
void display(Purchase obj[],int n)
Why can't you use a void display_vect(std::vector<Purchase>&vec); ? If you cannot change the API of display, consider calling your display_vect from your display member function.
Read about the rule of five.
I'm not completely sure what the issue is, or what you've been asked to do. But it's clear that display should not be a member function of Product. Member function of Product should be concerned with one particular product but display is printing all products, so it should be a stand-alone functon not a member function. Your code should look like this
class Product
{
...
};
void display(Purchase obj[],int n)
{
...
}
Then calling it from main is trivial.
int main()
{
...
display(P, n);
}
Trying to build a database using classes.
This is just an excerpt of the classes, my main() creates a bunch of students using the class Student. Each student then has an ID and Name that are inputted later. Additionally, each student will have an array of 2 slots which will hold info for their courses they're taking. Those courses are created using the class Course.
What I'm trying to figure out is how can I place the course info (courseID and courseName) into a slot of the student's courses array once I assign them a course (in other words, student A is now in class 1. I want the courseID and courseName of class 1 to be assigned to student A's courses).
I try to use the locations of each course created in the main but that proves difficult trying to output. Is it possible to be in the class Student and have it call a function from class Course? Any help be great. Thanks.
class Course {
protected:
int courseID;
char* courseName;
public:
Course() {
courseID = 0;
courseName = "";
}
void makeID(int id, char* name) {
courseID = id;
courseName = name;
}
int getID() {
return courseID;
}
char* getCourseName() {
return courseName;
}
};
class Student : public Course {
private:
int studentID;
char* studentName;
int classCount;
int courses[2]; //could I change to: Course courses[2]?
char name[30];
int id;
public:
Student() {
studentID = 0;
studentName[30];
classCount = 0;
courses[2];
}
void makeStudent() {
cout << "Input 9 digit student ID: ";
cin >> id;
studentID = id;
cin.ignore();
cout << "Input first and last name of the student: ";
cin.getline(name, 30, '\n');
studentName = name;
return;
}
int getstudentID() {
return studentID;
}
int getclassCount() {
return classCount;
}
char* getstudentName() {
return studentName;
}
void addClass(int course) {
if (classCount == 2) {
cout << "Max amount of courses reached." << endl;
}
else {
courses[classCount] = course;
classCount++;
}
return;
}
int returnClass(int course) { //can't figure out what to do
return courses[course]; //here.
}
};
At very first, you should get a clear image how your data model shall look like.
OK, we have bunch of courses and a bunch of students. Courses and students are totally unrelated (apart from students attending courses) concepts at first, so it won't make any sense one inheriting from the other...
Imagining the scenario does not only cover one single period (school year, semester, trimester, ...), courses might change over time as well as will the students.
So you might have a vector or another data structure storing courses on one hand and students on the other.
Students will attend courses, this can be reflected in two ways:
courses holding lists of all students attending them
students holding lists of all courses they attend
Depending on use case, it might be appropriate to implement both redundantly.
How would you install such a relation ship? Easiest (at a first glance, at least) would be X holding one or more pointers to Y in both scenarios.
class Course
{
std::vector<Student*> participants;
public:
// whatever you need...
};
class Student
{
std::vector<Course*> students;
public:
// whatever you need...
};
As I now use pointers to represent the relation ship, the data structures holding all courses and students must not invalidate these if adding or removing students from! std::vector<X> would do so, so you cannot use it. Alternatives would be std::vector<std::unique_ptr<X>> or std::list<X>. Actually, std::vector<X*> would work as well, but then it would be you who would need to care for deletion, if removing courses or students, so prefer one of the other solutions.
But why did I not use smart pointers for the courses' and students' vectors? We'd be forced to use std::shared_ptr then for, but we won't profit from: If a student leaves our institution, we'd have to eliminate her/him anyway and remove her/him from all courses being attended. So we don't profit from smart pointers in this scenario (can be totally different in other ones). Analogously if a course is cancelled.
So make sure in the destructors the classes that
a course is removed from all students' vectors in its own vector
student is unregistered from all courses in its vector
With these basics, you can get ID, name and other data for a specific course a student attends simply via the pointer in the vector.
If you often seek via a specific information, (e. g. by name), you might have a std::map as well, facilitating the lookup by the specific attribute. You might use such a map for the complete list of courses/students as well, then, though, be aware that pointers are only guaranteed to remain valid in std::map<X, Y>, not in std::unordered_map<X, Y>, so if you intend to use the latter, you'd have to go the way via smart pointer again as with the vector: std::unordered_map<X, std::unique_ptr<Y>>.
Question
Design a class Employee with name and employee number. Derive Manager, Scientist and Laborer classes. The manager class has extra attributes title and dues. The scientist class has extra attribute number of publications. The Laborer class has nothing extra. The classes have necessary functions for set and display the information.
My solution
#include<iostream>
#include<cstring>
using namespace std;
class employee
{
protected:
char *name;
int number;
public:
employee()
{
cout<<"enter employee name \n";
cin>>name;
cout<<"enter employee number \n";
cin>>number;
}
void display()
{
cout<<"name \t"<<name<<endl;
cout<<"number \t"<<number<<endl;
// inside class function is a inline function
}
};
class manager: private employee
{
float due;
char *title;
public:
manager( )
{
cout<<"due\t "<<endl;
cin>>due;
cout<<"title\t"<<endl;
cin>>title;
fflush(stdin);
}
void display()
{
employee::display(); //inside class function is a inline function
cout<<"due\t"<<due<<endl;
cout<<"title\t"<<title<<endl;
//inside class function is a inline function
}
};
class labour :private employee
{
public:
void display()
{
employee::display(); //inside class function is a inline function
}
};
class Scientist :private employee
{
int number;
public:
Scientist()
{
cout<<"publication number "<<endl;
cin>>Scientist::number;
}
void display()
{
employee::display();
cout<<" pub number "<<Scientist::number<<endl;
fflush(stdin);
} //inside class function is a inline function
};
int main()
{
manager m;
m.display();
Scientist s;
s. display();
labour l;
l.display();
return 0;
}
You don't allocate any memory for title or name, so you can't read into them from std::cin. Instead of using char* you should use std::string which will do all of the allocation for you:
std::string title;
std::string name;
In the constructor of empolyee you read into an uninitialized char*. Therefore it does not point to a valid block of memory where you could store the entered name to. You could do
name = static_cast<char*>(malloc( 32 * sizeof(char) ));
to allocate memory such that name points to valid memory, but you always waste memory or do not have enough for the input. Also you have to free the memory in the destructor.
As Peter Schneider wrote in the comment of this answer, another option is to use arrays of a fixed size as a member, e.g.
char name[MAX_NAME_LENGTH];
with a e.g. preprocessor defined
#define MAX_NAME_LENGTH 64
at the top of your file. This way the copy constructor does his job. With pointers as members, you always have to write them yourself, otherwise, the original class instance and copied instance will have a member pointer pointing to the same memory. So if one the copied instance changes the name, the original instance will have a changed name, too.
The easiest solution would be to use a std::string instead of char*. It allocates memory on its own and you don't have to free anything and copying works fine, too.
I am having trouble understanding some parts of the question for this program and would like to know why and how to type the program. Here are the parts I'm unable to understand:
The third member variable is a pointer to a double, pquiz. This will be used to dynamically allocate an array which will hold a student's quiz grades.
(Did I do this correctly?)
The fourth member variable is a double holding the average value of the quiz grades.
The class should have a one parameter constructor which accepts an int and will dynamically allocate the array of double quiz grades. Or the class can >have a two parameter constructor which accepts both a string and an int.
The int is the number of quiz grades
The constructor uses the new operator to allocate memory for the array of quiz grades.
If there are two parameters, the string is the student's name.
The class needs the usual mutator, accessor functions and a destructor function.
The class has an additional function, average(), which calculates the average of all the quiz grades held in the array pointed to by pquiz. It returns the double average value.
I'm suppose to print a students name, number of tests the student took, and the average. Here is my program so far:
#include <iostream>
#include <string>
using namespace std;
class TestScore{
private:
string name;
int grades;
double *pquiz;
double average;
public:
TestScore();
void setName(string);
void setGrades(int);
void setAverage(double);
string getName();
int getGrades();
double getPquiz();
double getAverage();
};
TestScore::TestScore()
{
name="?";
grades=0;
pquiz=0;
average=0;
}
void TestScore::setName(string name1)
{
name=name1;
getline(cin,name1);
}
void TestScore::setGrades(int grades1)
{
grades=grades1;
}
void TestScore::setAverage(double average1)
{
average=average1;
}
string TestScore::getName()
{
return name;
}
int TestScore::getGrades()
{
return grades;
}
double TestScore::getAverage()
{
return average;
}
int main()
{
TestScore exam;
TestScore *ts=&exam;
string name;
int grade;
double *pquiz;
double average;
double total=0.0;
int count;
cout<<"Enter student name: ";
exam.setName(name);
cout<<"How many quizzes are there? ";
exam.setGrades(grade);
cin>>grade;
pquiz=new double[grade];
for(count=0; count<grade; count++)
{
cout<<"Quiz "<<(count+1)<<": ";
cin>>pquiz[count];
}
for(count=0; count<grade; count++)
{
total+=pquiz[count];
}
average=total/grade;
cout<<exam.getName()<<" has an average of "<<average<<endl;
delete [] pquiz;
pquiz=0;
return 0;
}
If I understand correctly member grades holds the length of the array pointed to by member pquiz. Whenever grades is set pquiz must also reflect new change (old array should be deleted, new one should be created). In constructor must only create the array. In setGrades() must delete old and create new.
Because member pquiz is controlled (or owned) by the class TestScore it's only logical that it should be deleted when object TestScore is deleted (or in our lingo "when it goes out scope"). This is done in class destructor, which you should add to the class.
According to text there should be one more member function, average(), that calculates the average and stores the value in member average. This member should be renamed, for the sake of your sanity.
#include<iostream.h>
using namespace std;
class staticdemo
{
static int rollno;
string name;
public:
staticdemo()
{
cout<<"NAME: ";
getline(cin,name);
rollno++;
}
int getname()
{
cout<<name;
return 0;
}
static int getvalu()
{
return rollno;
}
};
int staticdemo::rollno=10;
int main()
{
int i,n;
cout<<"enter the number of studentd:";
cin>>n;
staticdemo s[n];
for(i=0;i<n;i++)
{
cout<<"name:"<<s[i].getname();
cout<<"\nroll no: "<<s[i].getvalu();
}
system("pause");
return 0;
}
I learning C++, i have a doubt in stack with array of object concept,
in my above program i get the names from user and rollno incremented through stack
while i retrieving list back it will give finally updated stack value, how to get the fully updated rollno values, (how to display the unique rollno for every names),
pls post your valuable solution
If I'm reading your question correctly, you want the rollno variable to be unique for each instance of the staticdemo class? Well then you can't have the member as static, because static members are shared among all instances of a class.
I think I roughly understand your question, although it seems a bit hard to get what you need.
What you have done is partially right, you use a static member variable "rollno" to record the count, however, if you really want what you need, you will need another non-static variable to record the index, e.g:
class staticdemo {
static int rollnoGlobal; // this will record the global count, used by everybody
int myRollno; //Non-static, this will record the rollno index for this particular object
string name;
public:
staticdemo() {
cout<<"NAME: ";
getline(cin,name);
myRollno = rollnoGlobal; // This is the step for each individual to remember its index
rollnoGlobal++;
}
int getname() {
cout<<name;
return 0;
}
static int getGlobalRollnoValue() {//return the global count;
return rollnoGlobal;
}
int getMyRollno() { // return the index or you call it rollno for this particular object
return myRollno;
}
};
int staticdemo::rollnoGlobal=10;
int main() {
int i,n;
cout<<"enter the number of studentd:";
cin>>n;
staticdemo s[n];
for(i=0;i<n;i++)
{
cout<<"name:"<<s[i].getname();
cout<<"\nroll no: "<<s[i].getMyrollno();
}
system("pause");
return 0;
}
Again if I was correct, the problem you faced is more like a understanding of static member variable and methods in C++ classes. This example you need two things:
A unique index for each variable, this is done by your original rollno static member.
Each staticdemo object must store its unique index. And this is the step you missed. After the global count increased, it increased for everybody because it is static. If you need to store it for each individual, you need another non-static member.
Side notes:
STACK is a very specific programming concept as pointed out by others, you question obviously does not need stack. You can try google what is a stack in programming.