Newbie questions about constructors and destructors

S

sieg1974

Hi,

I'm learning how to program in C++, and I came up with a couple of
questions.

1. Can I declare a constructor or destructor virtual? If so, please
provide me an example where I could use it.

2. Could a constructor be declared private? If so, how could I
instantiate an object of this class? I think I could use friend
methods to do it, but I'm not sure.

Thanks in advance,

Andre
 
V

Victor Bazarov

sieg1974 said:
I'm learning how to program in C++, and I came up with a couple of
questions.

1. Can I declare a constructor or destructor virtual? If so, please
provide me an example where I could use it.

A constructor cannot be virtual. A destructor can. Please read your
favourite C++ book about virtual destructors. Also, it is covered in
the FAQ (http://www.parashift.com/c++-faq-lite/).
2. Could a constructor be declared private? If so, how could I
instantiate an object of this class? I think I could use friend
methods to do it, but I'm not sure.

Yes, it can. You would leave instantiation of such class to the
class members or to the friends as you stated. Read about "named
constructor idiom" (or "the factory method"). This also is covered
in the FAQ.

Victor
 
O

Oystein Haare

Hi,

I'm learning how to program in C++, and I came up with a couple of
questions.

1. Can I declare a constructor or destructor virtual? If so, please
provide me an example where I could use it.

Constructor: No! (At least no directly)
Destructor: Yes. Do it whenever it is likely that someone will inherit
your class.
http://www.parashift.com/c++-faq-lite/virtual-functions.html#faq-20.5
2. Could a constructor be declared private? If so, how could I
instantiate an object of this class? I think I could use friend methods
to do it, but I'm not sure.

Yes it can, for example when using the singleton design pattern: you have
a static function that returns the one and only instance.
 
J

jeffc

sieg1974 said:
Hi,

I'm learning how to program in C++, and I came up with a couple of
questions.

1. Can I declare a constructor or destructor virtual?
No.

2. Could a constructor be declared private?
Yes.

If so, how could I
instantiate an object of this class? I think I could use friend
methods to do it, but I'm not sure.

class A
{
public:
static A* createA() { return new A; }
private:
A() {}
};
int main()
{
A* pA = A::createA();
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top