Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I want to create a Student object in C++ and it has the properties of name, major, age and id. The object initialization will be done in the main() part and Student object has the get and set methods for all the constructors. I want to print the student objects in the main() part but I get this error:
in C++98 's1' must be initialized by constructor, not by '{...}'
I am using GNU GCC Complier in Codeblocks. I haven't written specifically any code for compiling or debugging.
I tried to initialize the objects by assigning them to this, making them null, giving them zero and random values but they haven't worked.
Student.h file
#ifndef STUDENT_H
#define STUDENT_H
#include <iostream>
#include <string>
using namespace std;
class Student
{
public:
string name, major;
int age, id;
Student(string name, string major, int age, int id);
string getName();
void setName(string name);
string getMajor();
void setMajor(string major);
int getAge();
void setAge(int age);
int getId();
void setId(int id);
};
ostream & operator << (ostream &out, Student &s);
#endif // STUDENT_H
Student.cpp file
#include "Student.h"
#include <iostream>
using namespace std;
Student::Student(string newName, string newMajor, int newAge, int newId)
{
name = newName;
major = newMajor;
age = newAge;
id = newId;
}
string Student::getName(){
return name;
}
void Student::setName(string newName){
name = newName;
}
string Student::getMajor(){
return major;
}
void Student::setMajor(string newMajor){
major = newMajor;
}
int Student::getAge(){
return age;
}
void Student::setAge(int newAge){
age = newAge;
}
int Student::getId(){
return id;
}
void Student::setId(int newId){
id = newId;
}
ostream & operator << (ostream &out, Student &s)
{
out << "Name: " << s.getName() << " Major: " << s.getMajor() << " Age: " << s.getAge() << " Id:" << s.getId() << endl;
return out;
}
Main.cpp file
#include <iostream>
#include <string>
#include "Student.h"
using namespace std;
int main()
{
Student s1 {"John","MATH",24,123456};
Student s2 {"Steve","ENG",22,654321};
cout << s1 << endl;
cout << s2 << endl;
return 0;
}
I expect to print out the properties of the students as a list but when I run it the program crashes and I get this error:
** in C++98 's1' must be initialized by constructor, not by '{...}' **
I fixed my problem. There were a few problems so here I will explain my solutions in detail.
1-My code is written in C++11 syntax but I was using C++98 syntax so I changed my complier to C++11.
2-My initialization was wrong, I used new variables such as newName, newAge... to change the properties of the Student object.
3-My set methods were wrong so I changed them similar to my initialization.
4-I added an opeator to print out properties more easily.
All the changes are updated for the code in the question
Related
I am trying to create a class object s2 with some customized attributes and some attributes from default constructor however my output is the wrong output for the get_year function. It should be outputing 0 which is the key for FRESHMAN but it is out putting 2 instead. The rest of the code is outputting as expected:
#include <stdio.h>
#include <iostream>
#include <algorithm> // for std::find
#include <iterator> // for std::begin, std::end
#include <ctime>
#include <vector>
#include <cctype>
using namespace std;
enum year {FRESHMAN, SOPHOMORE, JUNIOR, SENIOR};
struct name
{
string firstName;
string lastName;
friend std::ostream& operator <<(ostream& os, const name& input)
{
os << input.firstName << ' ' << input.lastName << '\n';
return os;
}
};
class Student: name{
private:
name Name;
year Year;
int idNumber;
string Department;
public:
void setname(string fn="", string ln="")
{
Name.firstName =fn;
Name.lastName =ln;
}
name get_name()
{
return Name;
}
void set_year(year yr=FRESHMAN)
{
Year=yr;
}
year get_year()
{
return Year;
}
void set_ID(int ID=0)
{
idNumber=ID;
}
int get_ID()
{
return idNumber;
}
void set_Department(string Dept="")
{
Department=Dept;
}
string get_Department()
{
return Department;
}
};
int main()
{
Student s2;
s2.setname("Nikolai", "Khabeboolin");
s2.set_ID(12436193);
cout<<"ID is: "<< s2.get_ID()<<", name is "<< s2.get_name()<<", year in school is: "<<s2.get_year()<<", Department is "<<s2.get_Department()<<endl;
return 0;
}
Student lacks a constructor, so all its members are default initialized, and the default initialization of year Year and int idNumber is "no initialization", so reading from them is undefined behavior. Reading them might find 0, 2, a random value each time, or crash.
I see that your class contains a void set_year(year yr=FRESHMAN) member, but your code never called set_year, so no part of this executed.
You should make a default constructor for Student, or as Goswin von Brederlow stated, use year Year{FRESHMAN}; and int idNumber{-1}; when declaring the members, to give them default initializations.
By not explicitly declaring and defining a constructor, in this case Student(), you open yourself up to undefined behavior. Your constructor should call set_year(year yr=FRESHMAN) OR even better, just set the year itself.
Can anyone tell me why i get the error "name was not declared in the scope when running this?
Thanks.
class lrn11_class{
public:
void setName(string x){
name = x;
}
string getName(){
return name;
}
private:
string lrn11_name;
};
int main()
{
lrn11_class lrn11_nameobject;
lrn11_nameobject.setname("Zee");
cout << lrn11_nameobject.getname() << endl;
return 0;
}
This should work - see comments (BTW use std:: - Why is "using namespace std" considered bad practice?)
#include <iostream>
#include <string>
class lrn11_class{
public:
void setName(const std::string& x){ // Potentially saves copying overhead
name = x;
}
std::string getName() const { // Look up const and its uses
return name;
}
private:
std::string name; // - Used: string lrn11_name; but functions use name!
};
int main()
{
lrn11_class lrn11_nameobject;
lrn11_nameobject.setName("Zee"); // Fixed typo
std::cout << lrn11_nameobject.getName() << std::endl; // Ditto
return 0;
}
You have declare lrn11_name as a member varible for this class. But in set and get functions you are using name.
Other than than you need to call functions as you have defined.
so instead of :-
lrn11_nameobject.setname("Zee");
cout << lrn11_nameobject.getname() << endl;
You have to use following code :-
lrn11_nameobject.setName("Zee");
cout << lrn11_nameobject.getName() << endl;
Make sure that
#include <iostream>
using namespace std;
should be included.
I have just learnt some object oriented programming concepts in Python, but I want to transfer this knowledge to C++, and I have trouble with basic implementation that used to be easy using Python.
#include<iostream>
using namespace std;
class Animal{
char name;
int age;
public:
Animal(char name, int age);
};
Animal::Animal(char name, int age) {
this->name = name;
this->age = age;
}
int main()
{
Animal dog ("Megg", 10);
cout << "Name: " dog.name <<endl;
return 0;
}
When I compile this code, I get a lot of messages, such as:
error: no matching function for call to 'Animal::Animal(const char[5], int)'
note: Animal::Animal(char, int) <near match>
note: candidate expects 1 argument, 2 provided
Thanks!
you don't need to do this->name = name in your constructor definition
"Megg" is a string literal. You can cast "Megg" into const char * but not into a char (this was most likely causing your error).
or better yet. You can use the C++ Standard Library string class std::string
#include <iostream>
#include <string>
class Animal{
std::string name;
int age;
public:
Animal(std::string name, int age);
std::string getName() const;
int getAge() const;
};
Animal::Animal(std::string Name, int Age) {
name = Name;
age = Age;
}
std::string Animal::getName() const {
return name;
}
int Animal::getAge() const {
return age;
}
int main()
{
Animal dog ("Megg", 10);
std::cout << "Name: " << dog.getName() << std::endl; // Error in this line. Missing << between "Name: " and dog.name
return 0;
}
Some additional edits:
You should avoid using using namespace std as it takes everything in the Standard Library (from the files you've included) and puts it in the global namespace. You can instead use the scope resolution operator :: as seen above.
When you start working with multiple libraries you may encounter that both have a class named vector or string, or functions with the same name. The way to avoid this is to specify what namespace you want to use.
or alteratively you can do the following:
using std::cout;
using std::endl;
using std::string;
Additionaly in order for you program to work you need a way to access your object's member variables. You could do this by making the variables public or the better practice is to add accessor functions.
I am in the process of learning c++ and have a question regarding reading and writing objects to files.
I created a class called Person. In my main file I created two instances of the Person class. I write instance one to a file called "person.dat" and later read it back into the second instance I created. Everything is working as expected except that there is an exception that is thrown after the program closes. I am not sure why or what is causing it.
Exception: Unhandled exception at 0x55ABDF62 (msvcp120d.dll) in
Writing Binary Objects.exe: 0xC0000005: Access violation writing
location 0xFEEEFEEE.
Can anybody shed some light on this for me?
Code: Person.h
#include <iostream>
#include <string>
using namespace std;
class Person {
private:
string name;
string surname;
int age;
public:
Person();
Person(string, string, int);
void setName(string);
void setSurname(string);
void setAge(int);
string getName();
string getSurname();
int getAge();
};
Person::Person() {}
Person::Person(string _name, string _surname, int _age) {
setName(_name);
setSurname(_surname);
setAge(_age);
}
void Person::setName(string _name) {
name = _name;
}
void Person::setSurname(string _surname) {
surname = _surname;
}
void Person::setAge(int _age) {
age = _age;
}
string Person::getName() {
return name;
}
string Person::getSurname() {
return surname;
}
int Person::getAge() {
return age;
}
Code: Program.cpp
#include <iostream>
#include <fstream>
#include "Person.h"
using namespace std;
int main() {
//create person 1
Person person;
person.setName("Kobus");
person.setSurname("Beets");
person.setAge(24);
//write person 1 to file
ofstream out;
out.open("person.dat", ios::binary);
out.write(reinterpret_cast <char *> (&person), sizeof(person));
out.close();
//create person 2
Person person2;
person2.setName("John");
person2.setSurname("Doe");
person2.setAge(26);
//read person 1 from file into person 2
ifstream in;
in.open("person.dat", ios::binary);
in.read(reinterpret_cast <char *> (&person2), sizeof(person2));
in.close();
//print new person 2
cout << " " << person2.getName() << " " << person2.getSurname() << " is " << person2.getAge() << " year(s) old... \n\n ";
system("pause");
return 0;
}
You cannot directly write objects to a file in this way, unless you have a POD-style data structures (e.g. just simple C data types or a struct/class thereof, no pointers, no C++ data types).
In your case, Person has two std::string members, which itself contain pointers and other stuff, which will loose its meaning once written to file and re-read to memory.
You would need to add some more logic to write the actual string contents (see std::string::c_str(), std::string::data(), std::string::size()).
The exception is probably causes by the std::string desctructor, which tries to free or access memory which is already freed.
guys, I have the following code, but I'm getting error at compiling time... the error is at the end. Thanks
1st Class is "Person"
#ifndef PERSON_H//protecting .h files
#define PERSON_H//protecting .h files
#include <iostream>
#include <string>
using namespace std;
class Person
{
public:
Person();
Person(string first, string last)
{
firstName = first;
lastName = last;
}
virtual void setName(string first, string last)
{
firstName = first;
lastName = last;
}
virtual void setWeightAge(int w, int a)
{
weight = w;
age = a;
}
virtual string getFirstName()
{
return firstName;
}
virtual string getLastName()
{
return lastName;
}
virtual int getWeight()
{
return weight;
}
virtual int getAge()
{
return age;
}
virtual void printPerson()
{
cout << "Name: " << firstName << " " << lastName << endl;
cout << "Age: " << age << endl;
cout << "Weight: " << weight << endl;
}
protected:
string firstName, lastName;
int weight, age;
};
#endif
2nd Class is "Student"
#ifndef STUDENT_H//protecting .h files
#define STUDENT_H//protecting .h files
#include <iostream>
#include <string>
#include "Person.h"
using namespace std;
class Student : public Person
{
public:
Student();
Student(Person s)
{
sStudent = s;
}
virtual void setGPA(double g)
{
gpa = g;
}
virtual void setSchedule(string c, string t, string d)
{
stClass = c;
time = time;
days = d;
}
virtual void setGrade(char g)
{
grade = g;
}
virtual double getGPA()
{
if (grade == 'a') { gpa = 4.0; }
if (grade == 'b') { gpa = 3.0; }
if (grade == 'c') { gpa = 2.0; }
else gpa = 0;
return gpa;
}
virtual char getGrade()
{
return grade;
}
virtual void printSchedule()
{
cout << "Class | Days | Time " << endl;
cout << stClass << " | " << days << " | " << time << endl;
}
protected:
string stClass, time, days;
char grade;
double gpa;
Person sStudent;
};
#endif
and Main()
#include <iostream>
#include "Student.h"
using namespace std;
int main()
{
//creating a person
Person john("John", "Smith");
john.setWeightAge(180, 39);
john.printPerson();
//making john a student
Student johnStdntMath(john);
johnStdntMath.setSchedule("Math", "7:45", "M, W");
johnStdntMath.setGrade('b');
johnStdntMath.printPerson();
johnStdntMath.printSchedule();
system("pause");
return 0;
errors:
1>------ Build started: Project: Person, Configuration: Debug Win32 ------
1> main.cpp
1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall Person::Person(void)" (??0Person##QAE#XZ) referenced in function "public: __thiscall Student::Student(class Person)" (??0Student##QAE#VPerson###Z)
1>c:\users\jorge\documents\visual studio 2010\Projects\Person\Debug\Person.exe : fatal error LNK1120: 1 unresolved externals
}
I suggest you double check your is-A and has-A relationships.
Writing Student : public Person says that a Student is-A Person. But later, you have a member variable sStudent of type Person, which says a Student has-A Person, and I'm guessing is not what you really want.
Check out the answers to this question: Inheritance vs. Aggregation for better explanations.
Listen to your linker, it's just as it says: In constructor Student::Student(Person) you're referring to constructor Person::Person(), but you didn't define Person::Person(), not in a way the linker can see when it does its thing with the Student constructor.
Technically, because you are filling in sStudent in the Student constructor's body the compiler first default-initializes the Person object sStudent, and then assigns to it s, the Person parameter of the constructor. If you'd use the initializer list then the Person member wouldn't be default-initialized and then assigned to but rather copy-constructed right away:
Student(const Person& s) : sStudent(s) { }
But the question remains: Why are you publicly declaring a default constructor in Person and not define it?
Also, you have a leak in Student. The string and Person members of Student won't clean up because when a Student object destructs its destructor won't be called. The Person destructor will be called, but not the Student destructor, and the reason being that the destructor of Person is non-virtual.
One more thing: It's a bad idea in object-oriented design in general and C++ in particular to use inheritance for reuse. The reason is that this very often leads to a violation of the LSP. It can also bear a (not major but nonetheless) performance overhead for introducing a virtual table. But it's the correctness that suffers that matters when you pick inheritance when you should really be using delegation.
You are accessing the no argument constructor for Person when you create the johnStdntMath instance. You need to either
Implement Person::Person() or ...
Change Student::Student(Person s) to Student::Student(Person const& s)
There are some other problems in your code as well. Student is-a Person so there is no need for the Student class to have a Person member variable - it shares the instance variables of its base class by virtue of inheritance. In other words, Student extends Person so your program could be written:
int main() {
Student johnStdntMath;
johnStdntMath.setName("John", "Smith")
johnStdntMath.setWeightAge(180, 39);
johnStdntMath.setSchedule("Math", "7:45", "M, W");
johnStdntMath.setGrade('b');
johnStdntMath.printPerson();
johnStdntMath.printSchedule();
return 0;
}
I would also avoid the using namespace std; statement anywhere and especially in a header file. For example, your Student class contains a member variable named time. This will conflict with the std::time_t std::time(std::time_t*) function defined in <ctime> if that header is included before "student.h".
You haven't implement the default constructor Person(),you can write it like this:
Person():weight(0)
,age(0){};
If you just want to complier it, this is enough;
Here are some tips below:
1.Check your mind, does class Student really need a Person member. If you really need it, Student(Person) may add an explicit symbol:
explicit Student(const Person& s) : sStudent(s) {...};
2.In Person.h
protected:
string firstName, lastName;
int weight, age;
the protected may be private?