arry of pointers ( classes ) - c++

So I have these classes:
In main I wrote an array of pointers:
student *arry[10];
How can I make each cell point to an object of a different class?
For example :
I want the cell 0 , 2 , 4
point to an object of class medstudent
using ( new statement )
thank you
here is class medStudent
#include<iostream>
#include"student.cpp"
using namespace std;
class medStudent:public student {
public :int clinicH;
public:
medStudent(int ch, string n , int i ):student(n,i){
setClinicH(ch);
cout << "New Medecine Student" << endl;
}
~medStudent(){
cout << "Medecine Student Deleted" << endl;
}
medStudent(medStudent & ms):student(ms){
cout << "New Copy Medecined Student" << endl;
}
medstudent(){
}
void setClinicH(int ch){
clinicH = ch;
}
int getClinicH()const{
return clinicH;
}
void print()const{
student::print();
cout << "Clinical Hours: " << getClinicH() << endl;
}
};
Here is class student:
#include <iostream>
//#include"medstudent.cpp"
using namespace std;
class student//:public medstudent
{
public :
static int numberOfSaeeds;
const int id;
string name;
public:
~student(){
cout << "Delete Student: " << getName() << " " << endl ;
}
student(string n, int i):id(i){
setName(n);
cout << "Student with args" << endl ;
}
void setName(string n){
name = n;
}
string getName()const{
return name;
}
void print()const{
cout << "My name is: " << name << endl;
cout << "My ID is: " << id << endl;
}
void setNOS(int nos){
numberOfSaeeds = nos;
}
int getNOS(){
return numberOfSaeeds;
}
void printAddress()const{
cout << "My address is " << this << endl;
}
student * getAddress(){
return this;
}
student(student & sc):id(sc.id){
name = sc.name;
setName(sc.getName());
cout << "New Object using the copy constructor" << endl;
}
};
Here is main code:
#include<iostream>
using namespace std;
#include"time.cpp"
#include "student.cpp"
//#include"medstudent.cpp"
int main(){
student a1("asa" , 2);
student * a[10];
a[3]= new student("jj", 22 );
a[0] = new medStudent();
}

Since you explicitly declare a medStudent constructor the compiler will not create a default constructor for your class. And when you do new medStudent(); you are (explicitly) trying to invoke the default constructor, which doesn't exist.
That will give you a build error, one that should have been very easy to diagnose if you read it and most importantly shown it to us (when asking questions about build errors, always include the complete and unedited error output, including any informational output, in the body of the question, together with the code causing the error).
The solution? Call the existing parameterized constructor. E.g. new medStudent("foo", 123).
By the way, if you want inheritance to work okay, and the base-class destructor to be called when deleting an object of a child-class, then you need to make the destructors virtual.

Related

Trying to pass an array of pointers to objects, to a function of another class in C++ (not allowed to use vectors)

I have a class named Student. I create many student objects in my main (each object representing one student.)What i'm really trying to do is pass each one of these students to function enter of School class, representing that a student enters the school and then print his/her name etc.Here's the code:
my study.h file consists of:
#include <iostream>
#include <cstring>
using namespace std;
class Student
{
private:
string name;
int no_floor;
int no_classroom;
public:
Student(const string& nam,int no_fl,int no_cla)//constructor
: name(nam), no_floor(no_fl), no_classroom(no_cla)
{
cout << "A new student has been created! with name " << name << " heading to floor: "<< no_floor << " class: " << no_classroom << endl;
};
~Student() //destructor
{
cout << "A Student to be destroyed! with name " << name << " is at floor: " << no_floor << " class: " << no_classroom;
};
Then the School class:
class School
{
private:
Student* pointer_array[2];
public:
School()//constructor
{
cout << "A New School has been created!" << endl;
};
~School(){//destructor
cout << "A School to be destroyed!" << endl;
};
void enter(Student student, int stc=0/*student counter*/);
};
on my main.cpp file: (memory allocation for each student)
#include <iostream>
#include <cstring>
#include <study.h>
using namespace std;
int main(void)
{
//Student creation
int i,floor,classroom;
string stname;
Student* students[2];
for(i=0; i<2; i++)
{
cin >> stname;
cin >> floor;
cin >> classroom;
students[i] = new Student(stname, floor, classroom);
}
School sch;
for(i=0; i<2; i++)
{
sch.enter(*(students[i]),i);
}
for(i=0; i<2; i++)
{
delete students[i];
}
}
Lastly on my study.cpp file i've got the School class function where i'm trying to pass each object by reference and not by coping them to a new object:
#include <iostream>
#include <cstring>
#include <study.h>
using namespace std;
void School::enter(Student student, int stc/*student counter*/)
{
pointer_array[stc] = &student;
cout << "pointer array[" << stc << "]:" << pointer_array[stc] << endl;
//^ this cout prints the same adress for both students array[0]:0x1ffefffd20
// array[1]:0x1ffefffd20
}
Any ideas on how to pass pointers to all students and not just one. Again i'm trying to pass the array by reference.Thoughts?
here's the solution to this problem
School class:
class School
{
private:
Student* pointer_array[5];
public:
School()//constructor
{
cout << "A New School has been created!" << endl;
};
~School(){//destructor
cout << "A School to be destroyed!" << endl;
};
void enter(Student* student, int stc=0/*student counter*/);
};
Student class doesn't change:
class Student
{
private:
string name;
int no_floor;
int no_classroom;
public:
Student(const string& nam,int no_fl,int no_cla)//constructor
: name(nam), no_floor(no_fl), no_classroom(no_cla)
{
cout << "A new student has been created! with name " << name << " heading to floor: "<< no_floor << " class: " << no_classroom << endl;
};
~Student() //destructor
{
cout << "A Student to be destroyed! with name " << name << " is at floor: " << no_floor << " class: " << no_classroom;
};
Then main.cpp:
#include <iostream>
#include <cstring>
#include <study.h>
using namespace std;
int main(void)
{
//Student creation
int i,floor,classroom;
string stname;
Student* students[2];
for(i=0; i<2; i++)
{
cin >> stname;
cin >> floor;
cin >> classroom;
students[i] = new Student(stname, floor, classroom);
}
School sch;
for(i=0; i<2; i++)
{
sch.enter(students[i],i);
}
for(i=0; i<2; i++)
{
delete students[i];
}
}
Lastly the study.cpp function:
void School::enter(Student* student, int stc/*student counter*/)
{
pointer_array[stc] = student;
(pointer_array[stc])->print();
cout << " enters school!" << endl;
cout << "pointer array[" << stc << "]:" << pointer_array[stc] << endl;
}

Having trouble with objects and classes in C++

So, I defined the method displayStudInfo in the 'Student' Class and called it in the main function. But I'm getting the error "Function not declared in this scope". Can anyone please tell me why this is happening and what I can do to solve this problem?
#include <iostream>
#include <string>
using namespace std;
class Student{
public:
int age;
string name;
void enterInfo(){
cout << "Enter your age = " ; cin >> age;
cout << "Enter your name = "; cin >> name;
}
void displayStudInfo(Student s)
{
cout << "Age = " << s.age << ", name=" << s.name << endl;
}
};
int main(){
int size;
Student stud[100];
Student abir;
abir.enterInfo();
displayStudInfo(abir);
}
In your case void displayStudInfo(Student s) is a member function of Student so you have to call it on an instance of Student, the same way you did with enterInfo.
You can solve that in different ways. One way is to make that member function a free function by moving it out of the body of the Student
class Student{
public:
// … 
};
void displayStudInfo(Student s)
{
cout << "Age = " << s.age << ", name=" << s.name << endl;
}
int main(){
// … 
displayStudInfo(abir);
}
displayStudInfo is, in fact, a good candidate for a free function. Or you make it static which is similar to a free function, and access the static member function using Student::displayStudInfo(abir).
The other way would be to call displayStudInfo on abir in that case you don't need the Student argument, as abir is implicitly passed to displayStudInfo.
class Student{
public:
// … 
void displayStudInfo()
{
cout << "Age = " << age << ", name=" << name << endl;
}
};
int main(){
// … 
abir.displayStudInfo();
}
void displayStudInfo(Student s) hidden in side class.
So, its not accessible in main().
Try:
void displayStudInfo()
{
cout << "Age = " << age << ", name=" << name << endl;
}
call in main():
abir.displayStudInfo();
In C++, all member functions implicitly receive a parameter which points to the current object. This parameter is the this pointer.
Therefore, it doesn't make sense for you to specify an additional (explicit) parameter for the object in your definition of the function displayStudInfo.
It would make sense to rewrite the function definition to
void displayStudInfo()
{
cout << "Age = " << age << ", name=" << name << endl;
}
and to call it with
abir.displayStudInfo();
instead of
displayStudInfo(abir);
Alternatively, you could make the function displayStudInfo a non-member function, by putting it outside the declaration of class Student. In that case, you would have to keep the explicit parameter, because that parameter is only passed implicitly to member functions.

No match for "operator<<" in std::operator

#include <iostream>
#include <string>
using namespace std;
// your code
class Dog {
public:
int age;
string name, race, voice;
Dog(int new_age,string new_name,string new_race,string new_voice);
void PrintInformation();
void Bark();
};
Dog::Dog(int new_age,string new_name,string new_race,string new_voice) {
age = new_age;
name = new_name;
race = new_race;
voice = new_voice;
}
void Dog::PrintInformation() {
cout << "Name: " << name;
cout << "\nAge: " << age;
cout << "\nRace: " << race << endl;
}
void Dog::Bark(){
cout << voice << endl;
}
int main()
{
Dog buffy(2, "Buffy", "Bulldog", "Hau!!!");
buffy.PrintInformation();
cout << "Dog says: " << buffy.Bark();
}
I'm newbie in C++ and I'm unable to figure out the error.I am getting the error at buffy.Bark(),it seems like its unable to print something which returns void.
no match for operator<< in std::operator<< >(&std::cout),((const char)
Either declare member function Bark like
std::string Dog::Bark(){
return voice;
}
and call it like
cout << "Dog says: " << buffy.Bark() << endl;
Or do not change the function but call it like
cout << "Dog says: ";
buffy.Bark();
because the function has return type void.
Or take another dog from the dog kennel.:)
Bark is defined as a void function:
void Dog::Bark(){
cout << voice << endl;
}
This means that trying to do cout << buffy.Bark() in main is trying to cout a void type variable, which is not possible. It's likely you simply meant buffy.Bark();, which will already output for you.

object oriented programming,use of static function to count objects

I want to display the objects of the class and the number of objects by using a static function. I typed this code but it does not work. It gives an error Too many types indeclaration" and "undefined symbol getCount. Can anyone help me? where is actually error in this code?
#include<iostream>
#include<string>
class Bag {
private:
static int objectCount;
int Weight;
std::string Brand;
std::string Type;
std::string Material;
std::string Colour;
public:
Bag(int W, std::string B, std::string T, std::string M, std::string C) {
Weight = W;
Brand = B;
Type = T;
Material = M;
Colour = C;
objectCount++;
}
void print() {
std::cout << "\n";
std::cout << "Bag: \n\n";
std::cout << "Weight:\t\t" << Weight << "kg" << '\n';
std::cout << "Brand:\t\t" << Brand << '\n' << "Type:\t\t" << Type << '\n';
std::cout << "Material:\t" << Material << '\n' << "colour:\t\t" << Colour << std::endl;
}
static int getCount() {
return objectCount;
}
};
int Bag::objectCount = 0;
int main() {
Bag bag_1(2, "Slazanger", "Atheletic Bag", "Polyethylene", "Brown");
bag_1.print();
std::cout << "object count " << Bag::getCount() << '\n';
Bag bag_2(4, "Samsonite", "Travel Bag", "Synthetic Fibre", "Gray");
bag_2.print();
std::cout << "object count " << Bag::getCount() << '\n';
Bag bag_3(5, "Herschel", "Duffel bag", "Leather", "Black");
bag_3.print();
std::cout << "object count " << Bag::getCount() << '\n';
Bag bag_4(3, "Kewin Woods", "Hand Bag", "Fibre", "Blue");
bag_4.print();
std::cout << "object count " << Bag::getCount() << std::endl;
while(!std::cin.get());
return 0;
}
You are scoping it incorrectly, getCount is statically scoped to the translation
unit, not the class. Thus it has no symbol named objectCount available to it.
To fix it, merely put the method inside the class.
class Bag {
private:
static int objectCount;
int Weight;
string Brand,Type,Material,Colour;
public:
Bag(int W ,string B ,string T,string M,string C)
{
Weight=W;
Brand=B;
Type=T;
Material=M;
Colour=C;
objectCount++;
}
void print()
{
cout<<"\n";
cout<<"Bag: \n\n";
cout<<"Weight:\t\t"<<Weight<<"kg"<<endl;
cout<<"Brand:\t\t"<<Brand<<endl<<"Type:\t\t"<<Type<<endl;
cout<<"Material:\t"<<Material<<endl<<"colour:\t\t"<<Colour<<endl;
}
static int getCount()
{
cout<< objectCount;
}
};
Aditionally, Borland is a really old compiler and suprised to even still
hear it's name, last release was around 15 years ago so you should really
consider using clang, gcc or msvc and upgrading your learning materials to
something less ancient. There has been alot of evolution in terms of practices,
standards and compiler conformance.
For example, C++ headers don't have an extension, and other small things like that.
This is a working version of your code:
#include <iostream>
#include <cstring>
using namespace std;
class Bag {
private:
static int objectCount;
int Weight;
string Brand, Type, Material, Colour;
public:
Bag(int W, string B, string T, string M, string C) //constructor
{
Weight = W;
Brand = B;
Type = T;
Material = M;
Colour = C;
objectCount++;
}
void print() {
cout << "\n";
cout << "Bag: \n\n";
cout << "Weight:\t\t" << Weight << "kg" << endl;
cout << "Brand:\t\t" << Brand << endl << "Type:\t\t" << Type << endl;
cout << "Material:\t" << Material << endl << "colour:\t\t" << Colour
<< endl;
}
static int getCount() //static function to count objects
{
cout << objectCount;
};
};
int Bag::objectCount = 0;
int main() {
Bag bag_1(2, "Slazanger", "Atheletic Bag", "Polyethylene", "Brown");
Bag bag_2(4, "Samsonite", "Travel Bag", "Synthetic Fibre", "Gray");
Bag bag_3(5, "Herschel", "Duffel bag", "Leather", "Black");
Bag bag_4(3, "Kewin Woods", "Hand Bag", "Fibre", "Blue");
bag_1.print();
cout << "object count" << Bag::getCount();
bag_2.print();
cout << "object count" << Bag::getCount();
bag_3.print();
cout << "object count" << Bag::getCount();
bag_4.print();
cout << "object count" << Bag::getCount();
}
There were several mistakes in the version you posted:
in C++ you don't need the .h when including files
you were using cout without the std:: qualifier or adding using namespace std; to your source. Also, please read this.
your static function was not declared/defined inside your class definition
it should be int main instead of void main
One last note: I removed your #include <conio.h> which should probably read #include <conio> and getch because I compiled this on a linux machine. Feel free to add them back in if you want them.

error: ISO C++ forbids in-class initialization of non-const static member

this is the header file: employee.h
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
#include <iostream>
#include <string>
using namespace std;
class Employee {
public:
Employee(const string &first, const string &last)
Overloaded Constructor
: firstName(first),
firstName overloaded constructor
lastName(last)
lastName overloaded constructor
{ //The constructor start
++counter;
it adds one plus per each object created;
cout << "Employee constructor for " << firstName
<< ' ' << lastName << " called." << endl;
}
~Employee() {
Destructor
cout << "~Employee() called for " << firstName << ' '
<< lastName << endl;
Returns the first and last name of each object
--counter;
Counter minus one
}
string getFirstName() const {
return firstName;
}
string getLastName() const {
return lastName;
}
static int getCount() {
return counter;
}
private:
string firstName;
string lastName;
static int counter = 0;
Here is where i got the error. But, why?
};
principal program: employee2.cpp
#include <iostream>
#include "employee2.h"
using namespace std;
int main()
{
cout << "Number of employees before instantiation of any objects is "
<< Employee::getCount() << endl;
Here ir call te counter's value from the class
{
Start a new scope block
Employee e1("Susan", "Bkaer");
Initialize the e1 object from Employee class
Employee e2("Robert", "Jones");
Initialize the e2 object from Employee class
cout << "Number of employees after objects are instantiated is"
<< Employee::getCount();
cout << "\n\nEmployee 1: " << e1.getFirstName() << " " << e1.getLastName()
<< "\nEmployee 2: " << e2.getFirstName() << " " << e2.getLastName()
<< "\n\n";
}
end the scope block
cout << "\nNUmber of employees after objects are deleted is "
<< Employee::getCount() << endl; //shows the counter's value
} //End of Main
What is the problem?
I have no idea what's wrong.
I have been thinking a lot, but a i do not what is wrong.
The initialization of the static member counter must not be in the header file.
Change the line in the header file to
static int counter;
And add the following line to your employee.cpp:
int Employee::counter = 0;
Reason is that putting such an initialization in the header file would duplicate the initialization code in every place where the header is included.
According to a similar SO answer there is another approach, in particular suited for your current implementation (header-only library):
// file "Employee.h"
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
class Employee {
public:
Employee() {
getCounter()++;
}
~Employee() {
getCounter()--;
}
static auto getCount() -> std::size_t {
return getCounter();
}
private:
// replace counter static field in class context,
// with counter static variable in function context
static auto getCounter() -> std::size_t& {
static std::size_t counter = 0;
return counter;
}
};
#endif //EMPLOYEE_H
I took the liberty to use std::size for representing the non-negative employee count and trailing return syntax for functions.
Accompanying test (ideone link):
#include "Employee.h"
int main() {
std::cout << "Initial employee count = " << Employee::getCount() << std::endl;
// printed "count = 0"
Employee emp1 {};
std::cout << "Count after an employee created = " << Employee::getCount() << std::endl;
// printed "count = 1"
{
Employee emp2 {};
std::cout << "Count after another employee created = " << Employee::getCount() << std::endl;
// printed "count = 2"
}
std::cout << "Count after an employee removed = " << Employee::getCount() << std::endl;
// printed "count = 1"
return 0;
}