Can I have datamember as the object of the same class??????

#include<stdio.h>
#include<iostream>
using namespace std;


class student
{

int marks;
student*s;

public:



void display()
{
marks=75;
cout<<"marks are"<<marks<<endl;

}

};


int main()
{
student s1;
s1.display();
return 0;

}


I compiled and executed above program ...and its working absolutely fine...

I chose data memmber of student class as pointeer to the object of the same class(student*s;) and its working fine...How can this be possible?

How can I create the instance of a class as a data member of the same class.

Lets say when I am creating first object of this class(Student s1;)and then
when control goes through this statement(student*s;) it doesnt even have slightest idea of how much space this object will consume as it didnt constrct any object so far..Like that when I assume its going to infinite loop..I dont know what I think is right but it doesnt make even slightest sense to me.
Please let me know if we can have a clss have data memeber as the object of the same class?

Please let me know if below code is possible

#include<stdio.h>
#include<iostream>
using namespace std;


class student
{

int marks;
student s; //I chose object itself as data memmber not pointer

public:



void display()
{
marks=75;
cout<<"marks are"<<marks<<endl;

}

};


int main()
{
student s1;
s1.display();
return 0;

}

If this is not possible ...then why above program worked and why below didnt work?

I am new to c++ with million doubts ...please help


Thanks
Prasad



then why above program worked and why below didnt work?
The first works because of the pointer. The compiler knows the size of the pointer.

The second doesn't work because the compiler doesn't know the size of student
Endless recursion. If student would contain a student, that would contain a student, that would contain a student, that would contain a student, that would contain a student, ...

A pointer is not a student.
You are using student which is being defined. while declaring as pointer based on architecture 32/64 know the size of address which is required. hence for pointer it worked.
Thanks all

Its clear for me now


Thanks again!!l

Topic archived. No new replies allowed.