Why dose this code not work im trying to use a copy constructor but for some reason the program just hangs if i remove the code at line 31 and if i don't remove the line then the compiler gives this error:
error: '((myClass*)this)->myClass::ptr1' cannot be used as a member pointer, since it is of type 'int*'|
||=== Build finished: 1 errors, 0 warnings ===|
#include <iostream>
#include <stdlib.h>
usingnamespace std;
class myClass{
private:
int *ptr1;
public:
void set(int n){
*ptr1 = n;
}
// Member functions.
void display(){
cout << *ptr1;
}
void copy(int *ptr){
ptr1 = ptr;
}
int getLength() const{
returnsizeof(ptr1);
}
// Constructors
myClass(){
*ptr1 = 0;
}
myClass(const myClass &p){
int length = 0;
length = p.getLength();
ptr1 = newint[length];
*ptr1 = p.*ptr1;
}
}a;
main(){
myClass b(a);
b.set(50);
cout << "The value of the ptr1 of object b is: ";
b.display();
a.set(70);
cout << endl << "The value of the ptr1 of object ptr is: ";
a.display();
cout << endl << "The value of the ptr1 of object b is: ";
b.display();
}
To have the value of a pointer which is a member, the syntax is *p.ptr1. What you do looks lime a use for method pointer, which is what the compiler is complaining about.
Also, that code will only copy a single integer while newint[length] allocates an array.
Though this has nothing to do with crashing. You simply never allocate a.ptr1. You need to read up on pointers and dynamic memory more.
#include <iostream>
#include <stdlib.h>
usingnamespace std;
class myClass{
private:
int *ptr1;
public:
// Member functions.
void set(int n){
*ptr1 = n;
}
void display(){
cout << *ptr1;
}
// Constructors
myClass(){
ptr1 = newint;
*ptr1 = 0;
}
~myClass(){
delete ptr1;
}
// Copy Constructor.
myClass(const myClass &p){
ptr1 = newint;
*ptr1 = *p.ptr1;
}
}a;
main(){
myClass b(a);
b.set(50);
cout << "The value of the ptr1 of object b is: ";
b.display();
a.set(70);
cout << endl << "The value of the ptr1 of object a is: ";
a.display();
cout << endl << "The value of the ptr1 of object b is: ";
b.display();
}