mercredi 3 juillet 2019

Can the extraction operator be used on a dynamically allocated object?

I have been trying to use the overloaded extraction operator to populate a string variable of my dynamically allocated object, to which the string class throws an exception handler 0x4.

#include <string>
#include <fstream>
#include <iostream>
using namespace std;

class Myclass{
 friend istream& operator << (istream& ,Myclass&);

 protected:
  string anewname;
};

// default constructor
Myclass::Myclass(void) {}

istream& operator >> (istream& stream, Myclass& obj) {
    cout << "Enter name: " << endl;
    stream >> obj.anewname;
    return stream;
}

 //main.cpp
// global variable
Myclass* new_ptr[2];

 int main(){
 int j=0;
 cin>>*new_ptr[j];
return 0;
}

The string library class throws an exception error handling 0x4, which I suspect it is saying that I have a null pointer. But, I am trying to write to the object.

Aucun commentaire:

Enregistrer un commentaire