Class inside namespace and set function outside in C++ - c++

In this task i need to set and get number of soldiers outside of class and namespace (and call it in main properly)
namespace GeneralStaff
{
class Troops
{
private:
int nSoldiers;
public:
string name;
string rank;
Troops(string _name, string _rank, )
{
name= "Unknown";
rank= "RankUnknown";
}
};
} // namespace GeneralStaff
This is outside of class and function
void GeneralStaff::Troops setSoldierN(int n)
{
nSoldiers= n;
}
In main:
GeneralStaff::Troops;
Troops.setSoldierN(10);
I know that i need proper object declaration in main (source) and problem is with function set.

To define a method of the class outside the class, just use the scope resolution(::) operator. But for defining a function outside the class, you need to declare it in the class itself, which you have not done. Check the following code, it should work:
namespace GeneralStaff
{
class Troops{
private:
int nSoldiers;
public:
string name;
string rank;
void setSoldierN(int x);
Troops(string _name, string _rank)
{
name= _name;
rank= _rank;
}
};
}
void GeneralStaff::Troops::setSoldierN(int n){
nSoldiers= n;
}
Also, I have initialized name and rank according to the values passed in the constructor, because there is no need of passing them if you want to initialize the variables with a fixed value.
And the object in the main function should be created as follows:
GeneralStaff::Troops troop("John", "2");
troop.setSoldierN(10);

A external function should be defined as friend to access prive members of a class:
class Troops
{
friend void GeneralStaff::Troops setSoldierN(GeneralStaff &gs, int n);
...
};
and setSoldierN need to get an instance of Staff class to change its nSoldiers
void GeneralStaff::Troops setSoldierN(GeneralStaff &gs, int n)
{
gs.nSoldiers= n;
}

Related

global function and class reference

I want to send integer value in class to global function from main. How should I send it as a parameter,I am sending the parameters wrong
Tetris
{
private:
int num;
}
printBoard(Tetris &t);
int main()
{
Tetris tetris;
printBoard(board,tetris);
}
i want to send num , to printboard.
There are several problems with the shown code.
First, you're missing the class keyword when defining the class.
Second, the return type of the function is also missing.
Third, the function has only one parameter but you're passing two arguments.
i want to send num , to printboard
You can add a getter called getNum which you can use from inside your free function as shown below:
vvvvv------------->added this class keyword
class Tetris
{
private:
int num = 0; //don't forget to initialize
public:
//add a getter
int getNum() const
{
return num; //return a copy
}
};
vvvv----------------------->added return type as void
void printBoard(Tetris &t)
{
std::cout << t.getNum(); //use the getter
}
int main()
{
Tetris tetris;
printBoard(tetris);
}
Demo

Regarding default constructor an object initialization/usage in C++ OOP

I have recently started learning OOP in C++ and I started solving example tasks regarding it. I want to instantiate an object of the class CStudent after having created a default constructor for it. However the compiler cannot compile the code. I would like to ask why is that?
When you write inside your class:
CStudent();
CStudent(string name, string fn);
...you only declare two constructors, one default (taking no-argument) and one taking two strings.
After declaring them, you need to define them, the same way you defined the methods getName or getAverage:
// Outside of the declaration of the class
CStudent::CStudent() { }
// Use member initializer list if you can
CStudent::CStudent(std::string name, string fn) :
name(std::move(name)), fn(std::move(fn)) { }
In C++, you can also define these when declaring them inside the class:
class CStudent {
// ...
public:
CStudent() { }
CStudent(std::string name, string fn) :
name(std::move(name)), fn(std::move(fn)) { }
// ...
};
Since C++11, you can let the compiler generate the default constructor for you:
// Inside the class declaration
CStudent() = default;
This should work, As commented by Holt, You need to define constructor, You have just declared it.
#include <iostream>
#include <string>
#include <list>
using namespace std;
class CStudent {
string name = "Steve";
list<int> scores;
string fn;
public:
CStudent() {};
CStudent(string name, string fn);
string getName();
double getAverage();
void addScore(int);
};
string CStudent::getName() {
return name;
}
double CStudent::getAverage() {
int av = 0;
for (auto x = scores.begin(); x != scores.end(); x++) {
av += *x;
}
return av / scores.size();
}
void CStudent::addScore(int sc) {
scores.push_back(sc);
}
int main()
{
CStudent stud1;
cout<< stud1.getName()<< endl;
return 0;
}

How do I access member variables from one class into other using friend functions in C++?

I am using fried functions for the very time and was assigned to complete an incomplete code using friend functions as below.
//CODE GIVEN IN THE QUESTION NOT MEANT TO BE EDITED
#include<iostream>
using namespace std;
class store_keeper;
class item
{
char prod_name[30];
char prod_code[10];
float prod_price;
int stock_In_Hand;
public:
void get();
void print()const;
friend class store_keeper;
};
class store
{
int num_Of_Items;
item items[20];
public:
void get_details();
void print_details() const;
friend class store_keeper;
};
class store_keeper
{
char name[30];
char id[10];
public:
void get();
void print();
void stock_mgmt(store &);
};
//MY CODE
void item::get()
{
cin>>prod_name>>prod_code>>prod_price>>stock_In_Hand;
}
void item::print() const
{
cout<<prod_name<<prod_code<<prod_price<<stock_In_Hand;
}
void store::get_details()
{
cin>>num_Of_Items;
for(int i=0;i<num_Of_Items;i++)
{
items[i].get();
}
}
void store::print_details() const
{
for(int j=0;j<num_Of_Items;j++)
{
items[j].print();
}
}
void store_keeper::stock_mgmt(store &s)
{
for(int k=0;k<s.num_Of_Items;k++)
{
if(items[k].stock_In_Hand<10)
{
s.print_details();
}
}
}
//CODE GIVEN IN THE QUESTION NOT MEANT TO BE EDITED
main()
{
store s;
store_keeper sk;
s.get_details();
sk.stock_mgmt(s);
}
I had to display the details of the item for which the stock in hand is less than 10.I am getting an error that num_Of_Items was not declared in this scope and suggest any edits if any required.Thanks.
There are few problems with your code, and they are all located in this function:
void store_keeper::stock_mgmt(store &s)
^ ~~~~~~ 1
{
for(int k=0;k<s.num_Of_Items;k++)
{ ^^^^^^^^^^^^^^~~~~~~~~~~~~~ 2
if(s.items[k].stock_In_Hand<10)
{ ^^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 3
s.items[k].print();
} ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 4
}
}
1 - you need to give name to this parameter as it is needed inside your function
2 - when compiler see store_keeper::num_Of_Items it thinks you want to access a static variable of name num_Of_Items inside store_keeper class, but there is no such variable. What you want here is to use s. to read num_Of_Items from s which is of type store. You have befriended store_keeper with store so this is legal
3 and 4 - items is a field in store class, which is provided to your function as a parameter s, so use s. to access it.
And finally item has a print and not print_details
This will allow your code to compile, but probably more work is needed to make it work as expected.

C++ Container and Entity Classes

I'm new to the site (and to programming) so I hope I post this question appropriately and under all the proper guidelines of the site. Ok, here it goes:
So I pretty new to C++ and am trying to create classes for a program. I have to construct "container and entity classes", but where I'm struggling is trying to nail down the proper syntax for my getter and setter functions in the container class. So here's the code I have so far:
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string>
using namespace std;
const int MAX_STUDENTS=100;
const int MAX_COURSES=25;
const int NAME_SIZE=30;
const int COURSE_COLUMNS=4;
const int GRADE_ROWS=10;
//Entity Classes
class Course
{
//Two private member variables
private:
string courseText;
int courseID;
public:
//Constructor
Course(void)
{
//Just providing initial value to the two object variables
courseText;
courseID=-1;
}
//Setters and Getters for each variable
string getCourseText(){
return courseText;}
void setCourseText(string userEnteredText){
courseText = userEnteredText;}
int getCourseID(){
return courseID;}
void setCourseID(int userEnteredID){
courseID = userEnteredID;}
};
class Student
{
//Private member variables
private:
string studentText;
int studentID;
int** coursesAndGrades;
int enrolledCoursesCount;
int timesReallocatedColumns;
int timesReallocatedRows;
public:
//Constructor
Student(void)
{
//Just providing initial value to the object variables
studentText;
studentID=-1;
coursesAndGrades = new int*[GRADE_ROWS+1];
for(int i=0;i<(GRADE_ROWS+1);i++)
{
coursesAndGrades[i] = new int[COURSE_COLUMNS];
}
enrolledCoursesCount=0;
timesReallocatedColumns=0;
timesReallocatedRows=0;
}
//Setters and Getters for each variable
string getStudentText(){
return studentText;}
void setStudentText(string userEnteredText){
studentText = userEnteredText;}
int getStudentID(){
return studentID;}
void setCourseID(int userEnteredID){
studentID = userEnteredID;}
int getCoursesAndGrades(int gradeRow, int courseColumn){
return coursesAndGrades[gradeRow][courseColumn];}
void setCoursesAndGrades(int gradeRow, int courseColumn, int entry){
coursesAndGrades[gradeRow][courseColumn]=entry;}
int getEnrolledCoursesCount(){
return enrolledCoursesCount;}
void setEnrolledCoursesCount(int enrolledCount){
enrolledCoursesCount = enrolledCount;}
int getTimesReallocatedColumns(){
return timesReallocatedColumns;}
void setTimesReallocatedColumns(int reallocColumnCount){
timesReallocatedColumns = reallocColumnCount;}
int getTimesReallocatedRows(){
return timesReallocatedRows;}
void setTimesReallocatedRows(int reallocRowCount){
timesReallocatedRows = reallocRowCount;}
};
Now, I've got a container class called GradeBook which contains dynamically allocated arrays of these two entity class objects.
class GradeBook
{
private:
Course* courses;
Student* students;
public:
//Constructor
GradeBook(void)
{
courses = new Course [MAX_COURSES];
students = new Student [MAX_STUDENTS];
}
}
I'm trying to figure out the proper way to translate the setter and getter functions from my entity classes to the container class so I can change individual elements of each class object in the dynamically allocated array. These changes will happen in more public member functions in the container class, but I'm completely stumped. I hope this question makes sense, and I'm not looking for anyone to write all of the setters and getters for me, I just need someone to point me in the proper direction for the syntax. Thanks everyone who made it through this!
If you will have something like this:
class GradeBook
{
public:
...
Student& student(int idx) { /*some boundary check here*/
return students[idx]; }
}
then you can use that method as:
GradeBook theBook;
...
auto idOfFirstStudent = theBook.student(0).getStudentID();
You just need to decide what that student() method shall return: it can return reference (as above) or pointer to student (instance). In later case you can return nullptr in case of out-of-bound errors. In first case the only reasonable option is to throw an error.
So there's no magic needed here, but you do need to decide how you want to do it. One way would be to just write something like:
void GradeBook::setCourseText(int i, const string &txt) {
courses[i].setCourseText(txt);
}
BTW, I would highly recommend using std::vector and at() rather than new.

How do I declare a struct within a class?

I want to declare a struct within a class which is private and I want to give a character value to a variable in the same struct, but I can't initialize it or cin it:
class puple
{
private:
struct p
{
char name[25];
int grade;
};
public:
puple(){};
void setme()
{
this->p::grade=99;
this->p::name[25]='g'; //here is the problem
}
void printme()
{
cout<<"Name: "<<this->p::name<<endl;
cout<<"Grade: "<<this->p::grade<<endl;
}
};
void main()
{
puple pu1;
pu1.setme();
pu1.printme();
}
You've describe a type called "p" which is a struct. There is yet no thing of type p around. Therefore your
p->...
calls make no sense.
Try declaring
p pInstance;
in your class and using it, ie:
void setme()
{
this->pInstance.grade=99;
this->pInstance.name[25]='g'; //here is the problem
}
Note even with this your assignment to name[25] will fail as the allowed indices for that array are 0 up to 24 (totalling 25 elements).
You have two serious problems here
struct p
{
char name[25];
int grade;
};
This defines a struct type, named p. I think what you wanted to do was
struct
{
char name[25];
int grade;
} p;
This will declare a struct, named p, with the name and grade member variables.
Your second serious problem is that you assign:
this->p::name[25]='g'; //here is the problem
This assigns 'g' to the 26th element of the array name. (arrays are 0-indexed)
isn't it
struct { ... } p; // variable of struct-type definition.
not
struct p { ... }; // type 'struct p' definition.
?
Place the struct definition outside of the class using a typedef. By having the struct defined in your .cpp file it will not be visible outside of your class.
#include <iostream>
typedef struct _foo
{
int a;
} foo;
class bar
{
public:
void setA(int newa);
int getA();
private:
foo myfoo;
};
void bar::setA(int newa)
{
myfoo.a = newa;
}
int bar::getA()
{
return myfoo.a;
}
using namespace std;
int main()
{
bar mybar;
mybar.setA(17);
cout << mybar.getA() << endl;
return 0;
}