#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.
Related
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.
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)
So i need to get code of the structure#1 (e[0]) but i get the following error;
"error: request for member 'get_code' in 'emp1', which is of pointer type 'Employee*' (maybe you meant to use '->' ?)"
i don't really understand how to fix this. Plus, it's an assigment so i'm bound to use structures,and also, i don't know what "->" is, but if it's any operator or something, im not allowed to use it cause we haven't been taught that yet.
(Answers to the similar question suggest using -> so that doesnt work for me.)
i also tried using *(emp1).get_code()
#include <iostream>
#include <string.h>
using namespace std;
struct Employee{
private:
string code;
string name;
float salary;
public:
void set_code(string c){
code=c;
}
void set_name(string n){
name=n;
}
void set_sal(float s){
salary=s;
}
string get_code(){
return code;
}
string get_name(){
return name;
}
float get_sal(){
return salary;
}
};
int main(void) {
Employee e[2],*emp1,*emp2;
string c,n;
float s;
for (int i=0;i<2;i++){
cout<<"Enter code for employee "<<i+1;
cin>>c;
e[i].set_code(c);
cout<<"Enter name for employee "<<i+1;
cin>>n;
e[i].set_name(n);
cout<<"Enter salary for employee "<<i+1;
cin>>s;
e[i].set_sal(s);
}
*emp1=e[0];
cout<<emp1.get_code();
}
First of all, this line is not correct:
*emp1=e[0];
What your line does is assign the structure value 'e[0]' to the structure at pointer 'emp1'. However, the pointer 'emp1' is never initialized, so you'd end up writing in an invalid location.
What you need to write is:
emp1=&e[0];
That will actually set emp1 to the location of 'e[0]'.
Secondly, the symbol '->' is what you use when you want to access a member of a pointer.
In this case you should not write:
cout<<emp1.get_code();
But rather:
cout<<emp1->get_code();
The reason why you need to write that is that 'emp1' is a pointer. Thus, to access its member 'get_code', you need to use the symbol '->'.
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.