Is there any method to call class member functions? - c++

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);
}

Related

define book class with member function and store value

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.

In C++, what is the recommended way to create 'n' number of objects, where n is user defined. How can I do this?

I want the number of objects that my program creates, to be controlled by the user. What are the different ways to do this and when should I choose one approach over another?
#include<iostream>
using namespace std;
class
{
public :
int FullName;
int RollNumber;
in
{
public :
int FullName;
int RollNumber;
int age;
int marks;
}
voidt age;
int marks;
};
void main()
{
int n;
cout << "How many Students record you want :\t ";
cin >>n;
Data Student[n];
}
Like said before, use std::vector.
Your example however seems to work:
https://onlinegdb.com/HyHjwZddQ
If the number of items becomes fixed at the moment of creation, your best option is
std::make_unique<Data[]>(n)
But if you might need to change the group of items later (insert or remove), then
std::vector<Data>(n)

Why is this program crashing ? Did I wrongly allocate memory?

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.

Not understanding what is being asked and how to type them?

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.

stack concept with array of object in C++

#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.