I am writing c++ program.
This is snippet of main method:
Student * array = new Student[4]; int i = 0; for(char x = 'a'; x < 'e'; x++){ array[i] = new Student(x+" Bill Gates"); i++; } defaultObject.addition(array, 4); This line array[i] = new Student(x+" Bill Gates"); throws an error:
g++ -c -g -MMD -MP -MF build/Debug/Cygwin-Windows/Run.o.d -o build/Debug/Cygwin-Windows/Run.o Run.cpp In file included from Run.cpp:12: Assessment3.hpp:53:39: warning: no newline at end of file Run.cpp: In function `int main(int, char**)': Run.cpp:68: error: no match for 'operator=' in '*((+(((unsigned int)i) * 8u)) + array) = (string(((+((unsigned int)x)) + ((const char*)" Bill Gates")), ((const std::allocator<char>&)((const std::allocator<char>*)(&allocator<char>())))), (((Student*)operator new(8u)), (<anonymous>->Student::Student(<anonymous>), <anonymous>)))' Student.hpp:19: note: candidates are: Student& Student::operator=(Student&) make[2]: Leaving directory `/cygdrive/g/Aristotelis/C++/assessment3' make[1]: Leaving directory `/cygdrive/g/Aristotelis/C++/assessment3' make[2]: *** [build/Debug/Cygwin-Windows/Run.o] Error 1 make[1]: *** [.build-conf] Error 2 make: *** [.build-impl] Error 2 BUILD FAILED (exit value 2, total time: 3s) Student class is over here:
#include "Student.hpp" #include <string> using namespace std; Student::Student(){ in = "hooray"; } Student::Student(string in) { this -> in = in; } Student::Student(const Student& orig) { } Student::~Student() { } Student & Student::operator=(Student & student){ if(this != &student){ this->in = student.in; } return *this; } Header file is here:
#include <string> using namespace std; #ifndef STUDENT_HPP #define STUDENT_HPP class Student { public: Student(); Student(string in); Student(const Student& orig); virtual ~Student(); Student & operator=(Student & student); // overloads = operator private: string in; }; #endif /* STUDENT_HPP */ This part of program creates array of type Student and stores objects of type student. The the array is passed to compare the values according to bubble sort. What might be the problem?
x+" Bill Gates"doesn't do what you expect, either. It does not do string concatenation because neither argument is a string. Instead, it advances a pointer to the character array " Bill Gates" by as many positions as the code point ofx(e.g. forx=='a'in ASCII, it goes to the 97th character of " Bill Gates", which obviously doesn't exist) and then interprets whatever it finds there as C string. If you are lucky, you get a segmentation fault (or your platform's equivalent). Otherwise you most likely just get garbage.array[i] = *(new Student(x+" Bill Gates"));deletethe pointer returned bynewin that statement. It would leak memory every time it's used.array[i] = Student(), because that's trying to bind a non-const reference to a temporary, which is illegal.