Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

The Recursive Classes

Wednesday, January 13, 2016

2:16 PM

So What happens to occur in your programming style is that a class called students has courses

Students :
Courses
And you also happen to have another class called courses that has students and is perfectly legit is real
life and now you want to simulate this style in programming.

Courses:
Students

Now if you try to do it the traditional way.

class courses
{
students A;
};
class students
{
courses B;
};
C++ would just deny your commands and rebel.
It is perfectly fine for C++ to do that . Why? Because you are asking the computer to make infinite
compositions of a single class here is how:

course
students
course
students
So to avoid this non-sensical infinite ladder what you would use are POINTERS
So here is the basic concept:
In any one of the classes instead of using a new object in the stack you use a VIRTUAL OBJECT.
So what I mean is:

class courses
{
String name;
students* A ;
};

//pointer of student type

class students
{
String name;
courses B [ ];
};

Intro to progamming Page 1

Create a place in the heap where you can keep the common stuff essentially so let us look at the
memory pic

Course
CS200
A
Students
Ayesha
B

student

Now suppose that the student in the heap is actually referring to the student in the student object (i.e
Ayesha) How do we do that well, what you do is assign the name of the student object in the heap to be
equal to the student name in the stack so in essence now I am in a cycle
When I do this :
Course -> A->name OR student->name I should get the same result Ayesha and that
happened because I put one of the common things in the heap and two things can point to the same
values In the heap. Isn't this cool!
So we are probably done with the basic concept but there is still a problem here:

class courses
{
String name;
students* A ;
};

//pointer of student type

class students
{
String name;
courses B [ ];
};
When the compiler starts to read stuff it encounters an error at line 3 ,it does not know what a student
is what components it will have. So here you need to calm down the complier and say "Well you know
what, just hold on to this kind of pseudo declaration ,I am going to declare something called the student
but am not going into the nitty gritty right now BUT I WILL LATER" So after you say this the compiler
won't complain about your style of programming and will wait until you actually declare everything
about the class student. This is called forward declaration. And this is how you do in compilers language

class students;
class courses
{
String name;
students* A ;
};

//pointer of student type

class students
{
String name;
courses B [ ];
};

If you want to discuss it further we can do that too.. ;-)


Intro to progamming Page 2

You might also like