Re: few questions concerning classes
"alternativa" <alternativa.4@wp.pl> wrote in message
news:1146315379.192057.322930@g10g2000cwb.googlegroups.com
Hello,
I have a few questions concerning classes.
1)
Why some people use default constructos, i.e constructors with no
parameters? To me it doesn't make any sense, is there something I
should know? For example, I'd declare a class in a following way:
class Sample {
int number;
string title;
public:
Sample (int n, string t);
~Sample ();
}
What is the sense in adding also
Sample() {}; in public part of a class?
In some contexts, it is not possible to call anything other than a default
constructor, e.g.,
Sample * array = new Sample[10];
It is also sometimes the case that
a) a class has no data members, or
b) it is not known at the time of declaration what those data members need
to be initialized to.
2)
If I have a few classes containing lists and one main class containing
head pointers to these lists, should I write destructors for all the
classes separately, or is it enough to write a destructor for main
class only? For example:
class Numbers {
int num;
Numbers *numNext;
public:
Numbers () { /*constructor body*/ };
~Numbers () { /*empty*/ };
};
class Titles {
int tit;
Titles *titNext;
public:
Titles () { /*constructor body*/ };
~Titles () { /*empty*/ };
};
class Together {
*numHead;
*titHead;
public:
Together (){ /*constructor body*/ };
~Together(){ /*destructor body*/ };
};
Is this ok?
You haven't given the type of numHead and titHead. I presume you mean:
Numbers *numHead;
Titles *titHead;
Whether it is OK depends on the nature of the destructor. In Together's
destructor, you could iterate along each list and delete each link. It is
much simpler, however, to write:
~Numbers () { delete numNext; }
~Titles () { delete titNext; }
~Together(){ delete numHead; delete titHead; }
Simpler still is to use std::list.
3) inheritance problem
I've got the following base class:
class Person {
public:
string name;
int phone;
Person(string n, int p);
~Person();
}
and inherited class:
class Student {
int mark;
public:
Student(string n, int p, int m) ;
~Student();
}
I know I shoudl write the base class in a way that data are in a
private part,but then it doesn't work. How to deal with it?
"Doesn't work" isn't very helpful information. How doesn't it work? What are
you trying to do?
--
John Carson