I wrote this program but it is showing error
details was not declared in this scope.
How can I correct this code?
#include<iostream>
using namespace std;
class dealer
{
private:
char first_name[30],last_name[30],city[20],phone_number[20];
public:
void accept()
{
details[0].first_name:"Simran";
details[1].first_name:"Palak";
details[0].last_name:"Arora";
details[1].last_name:"Kaur";
details[0].city:"Amritsar";
details[1].city:"Jalandhar";
details[0].phone_number:1234567890;
details[1].phone_number:8987654321;
}
void display()
{
cout<<"Record of first person"<<endl;
cout<<"First name is "<<details[0].first_name<<endl;
cout<<"Last name is "<<details[0].last_name<<endl;
cout<<"City is "<<details[0].city<<endl;
cout<<"Phone number is "<<details[0].phone_number<<endl;
cout<<"Record of second person"<<endl;
cout<<"First name is "<<details[1].first_name<<endl;
cout<<"Last name is "<<details[1].last_name<<endl;
cout<<"City is "<<details[1].city<<endl;
cout<<"Phone number is "<<details[1].phone_number<<endl;
}
};
int main()
{
dealer details[2];
details[0].accept();
details[1].accept();
details[0].display();
details[1].display();
return 0;
}
You are attempting to access details within Dealer::accept(). However, details is a variable local to your main() function. Dealer::accept() is a member of the Dealer class and can only see member variables declared within that class.
Dealer cannot see the variable details that you've declared in main(). If you want the Dealer class to initialize certain members, consider writing functions to set those specific variables. For instance, to set first_name, write a function like:
void Dealer::setFirstName(std::string name)
{
strcpy(first_name, name.c_str()); // Consider changing the type of first_name to
// std::string. No need to use char arrays in this
// day and age
}
int main()
{
dealer details[2];
details[0].setFirstName("Simran");
details[1].setFirstName("Palak");
// etc...
}
Related
So I'm an newbie to programming and I have encountered a
case for which I suppose qualifies as an authentic question
in this awesome forum. Is there a way to write statements inside my get functions so that I can obtain all the changed data member values without having to create multiple get functions
for each data member?
Regards
I am practicing building programs which are easy to maintain by localizing the effects to a class's data members by accessing and manipulating the data members through their get and set functions. In this regard I have two data members for which I wish to change. After compiling, the set functions works well by changing the values but the get functions can only return one of the data member values at a time.
class GradeBook
{
public:
void setCourseName(string code,string name)
{
CourseCode = code;
CourseName = name;
}
string getCourseName()
{
return CourseCode;
return CourseName;
}
void displayMessage()
{
cout<<"Welcome to the GradeBook for: \n" <<getCourseName()
<<endl;
}
private:
string CourseName;
string CourseCode;
};//end class GradeBook
After compiling and running the program, the program outputs the CourseCode but the CourseName doesn't get displayed. I had to create two get functions each to obtain the two data members. I don't want to have 2 get functions to obtain the data member values. I just want to use one get function to keep the code at minimum.I wish to use one get function to return two values for each data member. I have already tried using one return statement and separated the data members with a comma.
Your idea of using return twice cannot work, the first return will return control to the caller and the second will never be executed. You should have got warning about it from your compiler.
I believe that an initial solution could be to use std::pair (docs: https://en.cppreference.com/w/cpp/utility/pair), see snippet below.
NOTE: using namespace std; (which is most likely what you are doing in the code you do not show), is a bad practice, consider using the fully qualified name
#include <string>
#include <utility>
#include <iostream>
//Bad practice, I added it only to keep differences with OP code small
using namespace std;
class GradeBook
{
public:
void setCourseName(string code,string name)
{
CourseCode = code;
CourseName = name;
}
std::pair<string, string> getCourseName()
{
return {CourseCode, CourseName};
}
void displayMessage()
{
//only in C++17
auto [code, name] = getCourseName();
cout<<"Welcome to the GradeBook for: \n" << code << " - " << name
<<endl;
}
private:
string CourseName;
string CourseCode;
};//end class GradeBook
Note that auto [code, name] is a feature called structured binding, available only in C++17, if you have an older compiler, you have to return a std::pair<std::string, std::string> and access its elements using the member variables first and second.
Now, std::pair is good for this contrived example, but, for your case, you might want to consider doing something a bit more readable, because the elements of the pair have the same type so the user of your library will have difficulties remembering what is the first and second element. So you might want to use a custom-made struct with some more meaningful names.
#include <string>
#include <utility>
#include <iostream>
//Bad practice, I added it only to keep differences with OP code small
using namespace std;
struct CourseCodeAndName{
std::string code;
std::string name;
};
class GradeBook
{
public:
void setCourseName(string code,string name)
{
CourseCode = code;
CourseName = name;
}
CourseCodeAndName getCourseName()
{
return {CourseCode, CourseName};
}
void displayMessage()
{
auto codeAndName = getCourseName();
cout<<"Welcome to the GradeBook for: \n" << codeAndName.code << " - " << codeAndName.name
<<endl;
}
private:
string CourseName;
string CourseCode;
};//end class GradeBook
See this example. Alternatively you can use std::tuple.
class GradeBook
{
/* ... */
public:
std::pair<std::string, std::string> get(){
return std::make_pair(CourseName, CourseCode);
}
};
int main()
{
GradeBook book1("Hello","World")
auto result = book1.get();
cout << result.first << result.second;
}
If you write:
return x,y;
or:
return x;
return y;
You should know that in first case you get the last value (you get y), and in second case you get the value of first return (you get x, because as soon as compiler see return, function will return the value, and then function will go in epilogue state (cleaning of stack memory assigned to function, both inline and non-inline function).
And about the use of get function it's normal. If you want to use the value to do something of logic (not to display), yes you should use a lot of get function. Instead if you want to display the values, use a void function, for example "void printData();", and inside it write code to print data. You probably setted the class variables as private (following the encapsulation rules) so you will have access to them inside the print function.
So I am calling a function which takes input as limit i, and array of objects h.
#include<iostream>
#include<vector>
using namespace std;
class hotel
{
private:
string name,add;
char grade;
int charge,no;
public:
void getdata();
void putdata();
void grade_print(int,hotel[]);
void room_charge();
void top2();
};
void hotel::getdata()
{
cout<<"Add Name: ";
getline(cin>>ws,name);
cout<<"Add Addres: ";
getline(cin>>ws,add);
cout<<"Enter grade,room charge and no. of rooms: ";
cin>>grade>>charge>>no;
}
void hotel::putdata()
{
cout<<name<<endl<<add<<endl<<grade<<endl<<charge<<endl<<no;
}
void hotel::grade_print(int num,hotel h[])
{
int i,j,k; char val;
for(i=0;i<num;i++)
{
val=h[i].grade;
for(j=0;j<num;j++)
{
if(h[j].grade==val)
{
cout<<h[j].grade<<endl;
h[j].grade=' ';
}
}
}
}
int main()
{
std::vector <hotel> h(1);
int i=0,j;
cout<<"Want to add hotel? Press 1: ";
cin>>j;
while(j==1)
{
h[i].getdata();
h.resize(2);
i++;
cout<<"Want to add more? Press 1 for yes, 0 for no: ";
cin>>j;
}
grade_print(i,h);
}
error here is showing that the grade_print is out of scope. Also the grade is a private member but is called by member function. So why is it showing that grade can't be called. Please tell me why so and what can I do to fix it?
Edit1: Declaring function as static void is not helping as the compiler is showing function can't be declared as static void.
D:\C++ Programs\testfile.cpp|30|error: cannot declare member function 'static void hotel::grade_print(int, hotel*)' to have static linkage [-fpermissive]|
From what I can understand, grade_print prints out information about a group of hotels passed as a parameter. If you have a function that acts on a group of a certain class, that function should not be a member of that class. Instead, it should just be a function not associated with any class. This also fixes your scope problem, as it would then have global scope.
If my argument seems weird, think about it like this. Let's say I have a class called number, as well as a function called print_nums which prints an array of numbers passed to it. Would I make print_nums a global function, or a member of the class number? The first one, right? The second one, although it would work, just doesn't really make sense.
grade_print(i, h);
A non-static member function should be called on a specific object like :
h[i].grade_print(i, h);
But, In your case grade_print have to be static, so it should be declared like this:
static void grade_print(int,hotel []);
And the definition goes like normal.
Also, after making grade_print static, you have to call it like this:
hotel::grade_print(i, h);
im new to learning c++ and iam now in the stage of creating a class that contains a vector of a class object, with methods to add new objects and print them all out.
Here is my code so far:
BankAccount.h:
#ifndef BANKACCOUNT_H
#define BANKACCOUNT_H
#include <string>
using namespace std;
class BankAccount
{
public:
BankAccount(string C_Name,int C_Balance);
/*
void SetCustomerName(string C_Name);
String GetCustomerName();
void SetCustomerBalance(int C_Balance);
int GetCustomerBalance();
*/
int deposit(int deposit_);
int withdraw(int withdraw_);
private:
string customer_name;
int customer_balance = 0;
int Deposit = 0;
int Withdraw = 0;
};
#endif // BANKACCOUNT_H
BankAccount.cpp:
BankAccount::BankAccount(string C_Name,int C_Balance)
{
customer_name = C_Name;
customer_balance = C_Balance;
}
int BankAccount :: deposit(int deposit_){
Deposit = deposit_;
Deposit = Deposit + customer_balance;
cout << "\nDeposit Balance = " << Deposit;
customer_balance = Deposit;
return customer_balance;
}
int BankAccount :: withdraw(int withdraw_){
Withdraw = withdraw_;
Withdraw = customer_balance - Withdraw;
customer_balance = Withdraw;
cout<<"After Withdraw Balance is "<<customer_balance;
return customer_balance;
}
Bank.h
#ifndef BANK_H
#define BANK_H
#include <vector>
#include "BankAccount.h"
using namespace std;
class Bank
{
public:
//variables , lists
vector<BankAccount> newAccount;
BankAccount bk;
// constructor
Bank();
};
#endif // BANK_H
Bank.cpp:
#include "Bank.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
Bank :: Bank()
{
string Customer_name = " ";
int Customer_balance = 0;
cout << "Add name please ";
cin >> Customer_name ;
cout << "How much balance?";
cin >> Customer_balance;
newAccount.push_back(bk(Customer_name,Customer_balance));
}
The BankAccount class is fine, the main problem is in the Bank class.
I have created the bank class to create a vectors of BankAccount , with methods that adds all the BankAccount and print them all out.
However this error keeps appearing under the constructor of Bank.cpp:
error: no matching function for call to 'BankAccount::BankAccount()'
It seems that whenever im trying to declare the class object inside the BankAccount vector , the error keeps on occuring.Can someone please explain what am i doing wrong and how to fix this?
The problem is not having a std::vector of BankAccounts. The problem is that your Bank class has a data member defined: BankAccount bk; Since you don't have any explicit constructor arguments, it tries to use the default constructor BankAccount(). There is no constructor declared, so you get a compilation error.
I suspect that you don't actually need that bk data member and should probably just remove it.
The next issue is when you try to push_back you are calling the bk object instead of constructing an object. What you want is to just have
newAccount.push_back(BankAccount(Customer_name,Customer_balance));
If you're using C++11 or greater (which it looks like you are) you can use emplace_back instead
newAccount.emplace_back(Customer_name,Customer_balance);
This would leave your Bank Account class as follows:
class Bank {
public:
std::vector<BankAccount> newAccount;
Bank();
};
Bank::Bank() {
std::string Customer_name = " ";
int Customer_balance = 0;
std::cout << "Add name please ";
std::cin >> Customer_name ;
std::cout << "How much balance?";
std::cin >> Customer_balance;
newAccount.emplace_back(Customer_name,Customer_balance);
}
You simply forgot to implement the constructor of your BankAccount class.
BankAccount::BankAccount(string C_Name,int C_Balance)
: customer_name(C_name)
, customer_balance(C_Balance)
{
// TODO;
}
As a side note, you probably want you input parameter C_name to be a const std::string& cName (using camelCase to be coherent, so a variable should never start with a capital letter, it's only used for Classes and Structs).
Usually, we use variable_ for private members (you did the opposite).
Another tip, variables should be initialized out of the body of the constructor.
EDIT:
// This is wrong
newAccount.push_back(bk(Customer_name,Customer_balance));
It should be:
// Construct a valid BankAccount object using it's constructor to fill the vector
newAccount.push_back(BankAccount(Customer_name, Customer_balance));
The variable bk is useless and needs a default constructor BankAccount::BankAccount() hence the error.
You have not defined a default constructor. When you use push_back it will try to default construct the object then copy the one you are passing in. You also default construct the member bk in Bank. You have 2 options to fix this problem.
Define a default constructor, ie. BankAccount() {
If you are in c++11 you can use vectors emplace_back routine. You will need to redesign to remove the bk member from Bank.
All objects contained by a class are constructed before the body of the constructor. In this case, your Bank object directly contains a BankAccount object, bk, which is constructed before the opening { in your Bank constructor:
Bank :: Bank()
// ... bk is initialized here....
{
You attempt to give bk some arguments later, in the call to newAccount.push_back, but it's too late; the bk object has been initialized.
To control how objects are initialized in a constructor, you must put calls to their constructors in the initialization list:
Bank :: Bank()
: bk(Customer_name,Customer_balance)
{
... but of course you haven't yet defined Customer_name or Customer_balance.
So let's back up a bit: why are you pushing an account into your Bank when you initialize the Bank? Why would an account even exist at this point? Why does Bank have bk as a member? (Why is that one account treated specially, when there's a whole vector of accounts that are also contained by the Bank?) And how are you going to add more accounts later?
So, try this: first, default-initialize the Bank:
Bank :: Bank() {}
...or, in the header (if you're using C++11 or C++14, which you should be):
Bank(void) =default;
Then, add a method for adding accounts:
Bank::addAcount(void)
{
// ... use stdin/stdout to get `customer_name` and `customer_balance`...
newAccount.emplace_back(customer_name,customer_balance);
}
(Note that you'll need to add push_back instead of emplace_back if you're not using C++11 or C++14.)
It seems that there is no standard constructor BankAccount::BankAccount() defined in your BankAccount.h.
But when you declare the standard constructor then you run in the following error
Error 1 error LNK2019: unresolved external symbol "public: __thiscall BankAccount::BankAccount(void)" (??0BankAccount##QAE#XZ) referenced in function "public: __thiscall Bank::Bank(void)" (??0Bank##QAE#XZ) [...]
Means that the member variable Bank::bk is declared but never defined.
So to compile your code successfuly I recommend to remove the declaration of the member variable bk in the class Bank. It makes no sense. Then do the following in your Bank class.
Bank::Bank()
{
string Customer_name = " ";
int Customer_balance = 0;
cout << "Add name please ";
cin >> Customer_name;
cout << "How much balance?";
cin >> Customer_balance;
BankAccount bankAccount(Customer_name, Customer_balance);
newAccount.push_back(bankAccount);
}
You will verify successfuly that the vector newAccount get filled with a new BankAccount object.
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.
#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.