C++ Constructor problems // Inherited class - c++

Initial problem solved. (which was a redefinition error)
Furthermore, I don't know how to create a Student constructor which delivers the following:
This is how I want my program / constructors to work:
//main.cpp
Student s1(4015885);
s1.print();
Student s2("Test", "Student", 22, 5051022);
s2.print();
The output should be as follows:
Standart
Name
18
4015885
Test
Student
22
5051022
s1 works, but s2 doesn't work, because I don't have a fitting constructor
This is my Person.h
#pragma once
#include <iostream>
#include <string>
using namespace std;
class Person {
public:
Person(string name = "Standard", string surname = "Name", int age**strong text** = 18);
//GET
//SET
void print();
protected:
string name, surname;
int age;
};
Person.cpp
#include <iostream>
#include <string>
#include "Person.h"
using namespace std;
Person::Person(string n, string s, int a) : name(n), surname(s), age(a)
{
cout << "Person constructor" << endl;
}
void Person::print() {
cout << name << endl << surname << endl << age << endl << endl;
}
Student.h
#pragma once
//#ifndef PERSON_H
//#define PERSON_H
#include "Person.h"
class Student : public Person {
public:
Student(int matrikel_nummer);
int get_matriculation_number();
void set_matriculation_number(int matriculation_number) {
this->matriculation_number = matriculation_number;
}
void print();
private:
int matriculation_number;
};
//#endif
Student.cpp
#include <iostream>
#include <string>
#include "Student.h"
using namespace std;
Student::Student(int matrikel_nummer) : Person(name, surname, age)
{
cout << "Student constructor" << endl;
this->matriculation_number = matriculation_number;
}
void Student::print() {
cout << name << endl
<< surname << endl
<< age << endl
<< matriculation_number << endl << endl;
}

In Student.h you have
Student(int matriculation_number) : Person(name, surname, age){};
Which declares and defines a constructor for Student. Then in Student.cpp you have
Student::Student(int matrikel_nummer) : Person(vorname, nachname, alter)
{
cout << "Student constructor" << endl;
this->matrikel_nummer = matrikel_nummer;
}
Which redefines the same constructor.
You either need to get rid of the constructor definition in the class
Student(int matriculation_number) : Person(name, surname, age){};
//becomes
Student(int matriculation_number);
or get rid of the constructor in the cpp file.
Also name, surname, age, vorname, nachname, alter do not appear anywhere in the code you have provided. This will not compile unless they declared somewhere else.
EDIT:
From the comments it looks like your Student constructor should be
Student(string n, string s, int a, int mn) : Person(n, s, a), matriculation_number(mn) {}
And you can put that in the header and you do not need a constructor definition in the cpp file.

Your error is here:
Student(int matriculation_number) : Person(name, surname, age){};
Remove the {} and the base ctor call:
Student(int matriculation_number);

You already defined the constructor body of student:
Student(int matriculation_number) : Person(name, surname, age){};
That is already a complete implementation of the constructor body, you should write this in the header:
Student(int matriculation_number);

Related

Inheritance in C++, how to initialize member variables in base class from derived class

i just opened up c++ today for the first time almost, and i tried doing some inheritance.
I have a class called Person and three classes that derive from Person called:
Retiree,
Adult,
Child.
The console asks for your age and in the case that you type 30 into the console i want to make a new adult object, and here i want to pass in the parameters: age, name and discount.
In java i would just call the constructor in the child class, as it has the super(a, b, c) in it. But when i try to do it here, it won't work, and i can't seem to figure out why.
Down below is two cpp files for Person and Adult showing their constructors and lastly the Main.cpp
I get this error when i try to create the object "Unhandled exception at 0x759EA842 in LearnCPP.exe: Microsoft C++ exception: std::bad_alloc at memory location 0x00AFF514."
Person.h
#pragma once
#include <String>
#include "BudgetAccount.h"
class Person
{
private:
public:
Person(int32_t age, std::string name);
int32_t getAge();
void setAge(int32_t age);
std::string getName();
void setName(std::string name);
protected:
int32_t age;
std::string name;
};
Person.cpp
#include "Person.h"
#include <String>
Person::Person(int32_t age, std::string name)
{
this->age = age;
this->name = name;
}
int32_t Person::getAge()
{
return age;
}
void Person::setAge(int32_t age)
{
this->age = age;
}
std::string Person::getName()
{
return name;
}
void Person::setName(std::string name)
{
this->name = name;
}
Adult.h
#pragma once
#include "Person.h"
class Adult : public Person
{
private:
double discount;
public:
Adult(double discount);
};
Adult.cpp
#include "Adult.h"
Adult::Adult(double discount) : Person(age, name)
{
this->discount = discount;
}
Main.cpp
#include <iostream>
#include "Person.h"
#include "Adult.h"
int main()
{
std::cout << "Hello Customer" << std::endl;
std::cout << "Down below you see a list of cities" << std::endl;
std::cout << "Please enter your name" << std::endl;
//Cin
std::string name;
std::cin >> name;
std::cout << "Please enter your age" << std::endl;
std::int32_t age;
std::cin >> age;
//Check if the entered age is child, adult or retiree
Adult user(50.0);
std::cout << "Please select which city you want to travel to" << std::endl;
return 0;
}
I think this is your problem:
Adult::Adult(double discount) : Person(age, name)
{
this->discount = discount;
}
You haven't passed in an age or name to this constructor, so it's using them from the parent class -- whose constructor hasn't been called yet.
As previously mentioned, you haven't passed the value for name and age.
One solution to this is that you can change the constructor to take in the values for age and name.
Another solution is that you can define default constructor. You can also set default values in the parameterised constructor.
Person::Person(int32_t age = 0, std::string name = ""){
this->age = age;
this->name = name; }

how do i initialize 2 static members belonging to 2 different derived classes

New to c++. I'm solving questions to understand better.
So, i have to make a program which has a parent class called Person and it has 2 derived classes named Student and Professor. The parent class Person has normal variables - std::string name and int age. The derived class Student has variables int sum, int marks[6] and static int cur_id. The derived class Professor has variables int publications and static int cur_id.
Now both the derived classes have 2 overloaded methods, getdata() - gets input from user and putdata() - prints data.
Also both have a static variable named cur_id which gets incremented when an object gets constructed.
Now the problem comes when i try to initialize the static variables using the below code -
int Student::cur_id;
int Professor::cur_id;
I get the following error -
'int Professor::cur_id': redeclaration of member is not allowed.
here is the full code -
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
class Person
{
protected:
std::string name;
int age;
public:
Person()
:age(0)
{}
};
class Professor : public Person
{
private:
int publications;
static int cur_id;
public:
Professor() //constructor
:Person(), publications()
{
++cur_id;
}
void getdata()
{
std::cin >> name >> age >> publications;
}
void putdata()
{
std::cout << name << " " << age << " " << publications << " " << cur_id << std::endl;
}
};
class Student : public Person
{
private:
int marks[6];
static int cur_id;
int sum;
public:
Student() //constructor
:marks{ 0 }, sum(0), Person()
{
++cur_id;
}
void getdata()
{
std::cin >> name >> age;
for (int index{}; index < 6; ++index)
{
std::cin >> marks[index];
sum += marks[index];
}
}
void putdata()
{
std::cout << name << " " << age << " " << sum << " " << cur_id;
}
};
int Student::cur_id;
int Professor::cur_id;
int main()
{
Student student;
student.getdata();
student.putdata();
Student nobita;
nobita.getdata();
nobita.putdata();
return 0;
}
Any help is appreciated, thanks
You should define cur_id in Professor class as static.

Storing Objects in an Array of a second Object

I have to create a small console application in C++ which will do the following:
Create class Subject which has next attributes: name of the subject, number of students and array of students who are attending that subject. After that createa class Student which has name and surname of the student as attributes. In Main file count how many duplicate names there are in each Subject.
I have few problems here. First one is that I don't know how to initialize an array in my Subject.h file. Second is how to actually put Student objects into Subject objects and compare the names in the end.
What I'd like output to look like:
Duplicate names in subjectA are: Michael.
Duplicate names in subjectB are: Nicholas, John.
Where subjectA and subjectB should be called C++ and C.
Here is my code so far (I googled for past hour or two about this problem of mine but I just couldn't find a proper answer/example).
NOTE: I'm including all these files for clarification.
Subject.h
#include <string>
#include <iostream>
using namespace std;
/*
* I should also have an array named `arrayOfStudents`
* which should store all students who are attending
* that Subject.
*/
class Subject
{
public:
Subject();
Subject(Subject &subject);
Subject(string nameOfSubject, int numberOfStudents);
~Subject();
const string getNameOfSubject();
const int getNumberOfStudents();
void setNameOfSubject(string nameOfSubject);
void setNumberOfStudents(int numberOfStudents);
void print();
private:
string nameOfSubject;
int numberOfStudents;
};
Subject.cpp
#include <iostream>
#include "Subject.h"
using namespace std;
Subject::Subject()
{
}
Subject::Subject(string nameOfSubject, int numberOfStudents)
{
this->nameOfSubject = nameOfSubject;
this->numberOfStudents = numberOfStudents;
}
Subject::Subject(Subject &Subject) : nameOfSubject(Subject.getNameOfSubject()), numberOfStudents(Subject.getNumberOfStudents())
{
}
Subject::~Subject()
{
cout << "Object is destroyed" << endl;
}
const string Subject::getNameOfSubject()
{
return nameOfSubject;
}
const int Subject::getNumberOfStudents()
{
return numberOfStudents;
}
void Subject::setNameOfSubject(string nameOfSubject)
{
nameOfSubject = this->nameOfSubject;
}
void Subject::setNumberOfStudents(int numberOfStudents)
{
numberOfStudents = this->numberOfStudents;
}
void Subject::print()
{
cout << "Subject: " << nameOfSubject << " :: Number of students: " << numberOfStudents << endl;
}
Student.h
#include <string>
#include <iostream>
using namespace std;
class Student
{
public:
Student();
Student(Student &student);
Student(string name, string surname);
~Student();
const string getName();
const string getSurname();
void setName(string name);
void setSurname(string surname);
void print();
private:
string name;
string surname;
};
Student.cpp
#include <iostream>
#include "Student.h"
using namespace std;
Student::Student()
{
}
Student::Student(string name, string surname)
{
this->name = name;
this->surname = surname;
}
Student::Student(Student &student) : name(student.getName()), surname(student.getSurname())
{
}
Student::~Student()
{
cout << "Object is destroyed" << endl;
}
const string Student::getName()
{
return name;
}
const string Student::getSurname()
{
return surname;
}
void Student::setName(string name)
{
name = this->name;
}
void Student::setSurname(string surname)
{
surname = this->surname;
}
void Student::print()
{
cout << "Student: " << name << " " << surname << endl;
}
Main.cpp
#include <iostream>
#include "Subject.h"
#include "Student.h"
using namespace std;
int main()
{
/*
* First three students should attend first Subject
* while other four the second Subject.
* Also note that only names matter and not surnames.
*/
Student stA("Michael", "Doe");
Student stB("Michael", "Doe");
Student stC("Thomas", "Doe");
Student stD("Nicholas", "Doe");
Student stE("Nicholas", "Doe");
Student stF("John", "Doe");
Student stG("John", "Doe");
Subject subjectA("C++", 3);
Subject subjectB("C", 4);
return 0;
}
1) Get an array of Students into your Subject object: you probably want to use vectors instead of arrays here:
in subject.h add
#include "Student.h"
public:
void addStudent(Student student);
private:
std::vector<Student> students_;
in subject.cpp add
void Subject::addStudent(Student student)
{
this->students_.push_back(student);
}
If you want to extract the student list somehow later, you need to write a function to access it (or make it public).
2) For finding duplicates, look here
Checking for duplicates in a vector
You have to pay attention: the Student objects are in your subject object, not the student names. You have to extract them first and e.g. put them in a vector.
Your task definition sais you should have an array of Students attribute of the Subject class, but i don't see this in your Subject class definition.
And maybe an add Student method and then iterate over the array.

error in C++: out-of-line definition

CustomerInfo.cpp
#include "CustomerInfo.h" // <==== Funtion Definition
CustomerInfo::CustomerInfo() // <==== The Scope Resolution which is two colons :: gives me access to the class
{
newZipCode = 0;
}
CustomerInfo::CustomerInfo(string name, string address, int zipCode)
{
newName = name;
newAddress = address;
newZipCode = zipCode;
}
CustomerInfo::~CustomerInfo()
{
}
string CustomerInfo::getName() const
{
return newName;
}
string CustomerInfo::getAddress() const
{
return newAddress;
}
int CustomerInfo::getZipCode() const
{
return newZipCode;
}
The main.cpp file
#include <iostream>
#include <string>
#include "CustomerInfo.h"
using namespace std;
int main()
{
string name;
string address;
int zipCode;
cout << "Enter your name: ";
getline (cin, name);
cout << "Enter your address" << endl;
getline (cin, address);
cout << "Enter your ZipCode: ";
cin >> zipCode;
CustomerInfo Real_1(name, address, zipCode);
cout << endl << " Name: " << Real_1.getName() << endl <<
"Address: " << Real_1.getAddress() << endl <<
"ZipCode: " << Real_1.getZipCode() << endl;
return 0;
}
The CustomerInfo.h file
#ifndef CUSTOMERINFO_H
#define CUSTOMERINFO_H
// Header ==> Function Declaration
#include <iostream>
#include <string>
using namespace std;
class CustomerInfo
{
public:
CustomerInfo(); // <==== Default Constructor
CustomerInfo(string, int); // <==== Overload Constructor
~CustomerInfo(); // <===== Destructor - Done using an object it will be destroyed out of memory'
string getName() const; // <==== Accessor Functions - Return member variables one value at a time. In addition, no void function will be used.
// getName - returns name of person
string getAddress() const;
// getAddress - returns address of person
int getZipCode() const;
// getZipCode - returns zipcode of person
private:
//Member Variables
string newName;
string newAddress;
int newZipCode;
}; // <=== Requires semicolon after brackets for classes
#endif // CUSTOMERINFO_H
The error I receive is out-of-line definition of 'CustomerInfo' does not match any declaration in 'CustomerInfo'
The following line is the error
CustomerInfo::CustomerInfo(string name, string address, int zipCode)
Your problem seems to be that you define a constructor
CustomerInfo::CustomerInfo(string name, string address, int zipCode)
which does not appear in the class definition (in CustomerInfo.h). The closest one is
CustomerInfo(string, int);
but it doesn't match the signature. Just replace it with
CustomerInfo(string name, string address, int zipCode);
to your class definition in the header file.

Setting up linked list class with templates?

I am trying to implement a linked list using a class template, however each of my classes that I want in the list all inherit from an Account class. I have attempted to template the linked list class as account however Ive come into errors I can't resolve. Any ideas as to how I can go about this?
The error exists within the customer.cpp class where it says
14 IntelliSense: a value of type "Account *" cannot be assigned to an entity of type "CurrentAccount *" f:\Further C++\Assignment with Templates\Assignment\Customer.cpp 22 9 Assignment
Customer class:
#ifndef CUSTOMER_H
#define CUSTOMER_H
#include <iostream>
#include <string>
#include "Account.h"
#include "AccountLinkedList.h"
using namespace std;
class Customer
{
private:
string name;
string telNo;
int doorNum;
string street;
string postcode;
string sex;
string dob;
AccountLinkedList <Account> accountList; //Here is the linkedList templated as Account class
Account * head;
Account * aNode;
public:
int customerID;
Customer * next;
//Customers personal details
Customer(int id, string customerName, string gender, int doorNumber, string customerPostcode, string dateOfBirth)
: customerID(id), name(customerName), sex(gender), doorNum(doorNumber), postcode(customerPostcode), dob(dateOfBirth)
{
};
string getName();
void addAccount(int choice);
void showPersonDetails();
void updatePersonDetails();
};
#endif
Here is the Customer.cpp file:
#include "Customer.h"
#include "Account.h"
#include "CurrentAccount.h"
#include "JuniorCurrentAccount.h"
#include "SavingsAccount.h"
#include "CorporateSavingsAccount.h"
#include "StudentSavingsAccount.h"
#include <string>
using namespace std;
void Customer::addAccount(int choice)
{
int id; // temp account ID
switch(choice)
{
/*Current account + JuniourCurrentAccount both inherit from Account class*/
case 0: CurrentAccount * aNode;
CurrentAccount * head;
/*the two lines below give the error on the = sign*/
aNode = accountList.CreateNode(id/*newaccountID*/);
head = accountList.InsertFirst(head, aNode);
break;
case 1: JuniorCurrentAccount * aNode;
JuniorCurrentAccount * head;
aNode = accountList.CreateNode(id);
head = accountList.InsertFirst(head, aNode);
}
}
string Customer::getName()
{
return name;
}
void Customer::showPersonDetails()
{
cout << name << " details" << endl;
cout << "===============================" << endl;
cout << "sex: " << sex << endl;
cout << "dob: " << dob << endl;
cout << "doorNum: " << doorNum << endl;
cout << "postcode: " << postcode << endl;
cout << "===============================" << endl;
}
Here is the current Account class that inherits from account:
#ifndef CURRENTACCOUNT_H
#define CURRENTACCOUNT_H
#include <iostream>
#include <string>
#include "Account.h"
using namespace std;
class CurrentAccount : Account
{
private:
double intRate;
double balance;
protected:
public:
CurrentAccount * next;
CurrentAccount(int accountNumber, double interestRate, double setBalance) : Account(accountNumber)
{
accountType = "Current Account";
intRate = interestRate;
balance = setBalance;
}
};
#endif