Wednesday 31 August 2011

10 Amazing Animal Facts

10 Amazing Animal Facts

The animal kingdom has long been a mysterious one for humans and every day we learn something new about it. This is a list of ten little known facts about animals.
10. Crocodiles Eat Stones
Croc
The stomach of a crocodile is a rocky place to be, for more than one reason. To begin with, a croc’s digestive system encounters everything from turtles, fish and birds to giraffes, buffaloes, lions and even (when defending territory) other crocodiles. In addition to that bellyful-o’-ecosystem, rocks show up too. The reptiles swallow large stones that stay permanently in their bellies. It’s been suggested these are used for ballast in diving.
9. Whale Milk is 50% Fat

Whale
Nursing a newborn is no “small” feat for the whale, whose calf emerges, after 10 to 12 months in the womb, about a third the mother’s length (that’s a 30-foot baby for the Blue whale). The mother squirts milk into the newborn’s mouth using muscles around the mammary gland while the baby holds tight to a nipple (yes, whales have them). At nearly 50 percent fat, whale milk has around 10 times the fat content of human milk, which helps calves achieve some serious growth spurtseas much as 200 pounds per day.
8. Birds Recognize Landmarks
Eagles-Birds Mg0752
Can you imagine a road trip vacation without missed exits, stubborn drivers or map-folding disasters? Of course noteyou’re not a bird. Pigeons can fly thousands of miles to find the same roosting spot with no navigational difficulties. Some species of birds, like the Arctic tern, make a 25,000 mile round-trip journey every year. Many species use built-in ferromagnets to detect their orientation with respect to the Earth’s magnetic field. A November 2006 study published in Animal Behaviour suggests that pigeons also use familiar landmarks on the ground below to help find their way home
7. Beavers have Longer Days in Winter
Beaver-T0269
Beavers become near shut-ins during winter, living off of previously stored food or the deposits of fat in their distinctive tails. They conserve energy by avoiding the cold outdoors, opting instead to remain in dark lodgings inside their pile of wood and mud. As a result these rodents, which normally emerge at sunset and turn in at sunrise, have no light cues to entrain their sleep cycle. The beaver’s biological sense of time shifts, and she develops a “free running circadian rhythm” of 29-hour days.
6. Mole-Rats are not Blind
Molerat
With their puny eyes and underground lifestyle, African mole-rats have long been considered the Mr. Magoos of rodents, detecting little light and, it has been suggested, using their eyes more for sensing changes in air currents than for actual vision. But findings of the past few years have shown that African mole-rats have a keen, if limited, sense of sight. And they don’t like what they see, according to a report in the November 2006 Animal Behaviour. Light may suggest that a predator has broken into a tunnel, which could explain why subterranean diggers developed sight in the first place.

5. Baby Chicks are Altruistic

Babybirds Miller 061705
It’s a mistake to think of evolution as producing selfish animals concerned only with their own survival. Altruism abounds in cases where a helping hand will encourage the survival of genetic material similar to one’s own. Baby chicks practice this “kin selection” by making a special chirp while feeding. This call announces the food find to nearby chicks, who are probably close relations and so share many of the chick’s genes. The key to natural selection isn’t survival of the fittest animal. It’s survival of the fittest genetic material, and so brotherly behavior that favors close relations will thrive.
4. Many Fish Swap Sex Organs
Dsc00535 School Fish
With so many land creatures to wonder at, it’s easy to forget that some of the weirdest activities take place deep in the ocean. The strange practice of hermaphroditism is more common among species of fish than within any other group of vertebrates. Some fish change sex in response to hormonal cycle or environmental changes. Others simultaneously possess both male and female sex organs.
3. Giraffes have Unique Blood Flow
Giraffes
The stately giraffe, whose head sits some 16 feet up atop an unlikely pedestal, adapted his long neck to compete for foliage with other grazers. While the advantage of reach is obvious, some difficulties arise at such a height. The heart must pump twice as hard as a cow’s to get blood up to the brain, and a complex blood vessel system is needed to ensure that blood doesn’t rush to the head when bent over. Six feet below the heart, the skin of the legs must then be extremely tight to prevent blood from pooling at the hooves.
2. Elephants are Smart
Lgelephantsonroad
Elephants have the largest brain, nearly 11 pounds on average of any mammal that ever walked the earth. Do they use that gray matter to the fullest? Intelligence is hard to quantify in humans or animals, but the encephalization quotient (EQ), a ratio of an animal’s observed brain size to the expected brain size given the animal’s mass, correlates well with an ability to navigate novel challenges and obstacles. The average elephant EQ is 1.88. (Humans range from 7.33 to 7.69, chimpanzees average 2.45, pigs 0.27.) Intelligence and memory are thought to go hand in hand, suggesting that elephant memories, while not infallible, are quite good.

1. Parrots Understand
Redloredparrots
Parrot speech is commonly regarded as the brainless squawking of a feathered voice recorder. But studies over the past 30 years continually show that parrots engage in much more than mere mimicry. Our avian friends can solve certain linguistic processing tasks as deftly as 4-6 year-old children. Parrots appear to grasp concepts like “same” and “different”, “bigger” and “smaller”, “none” and numbers. Perhaps most interestingly, they can combine labels and phrases in novel ways. A January 2007 study in Language Sciences suggests using patterns of parrot speech learning to develop artificial speech skills in robots.

Saturday 27 August 2011

India's Top 50 Engineering Colleges 2011

India's Top 50 Engineering Colleges 2011

Ranking the top colleges is a very difficult task. While it is relatively easy to create clusters of colleges, it is differentiating within clusters that became the most difficult exercise. So for the first time in the country we have used balanced scorecard methodology to arrive at the ranking of the top 50 colleges. Ranking methodology: We scanned the last five year rankings of about 241 colleges and normalised their ranks, by assigning differential weights to subjective and objective ranking. Such a process is used to develop clusters of institutions. The research standing of individual institutions were further used to refine the clusters and remove the odd men out. Individual clusters were ranked serially. In each of these clusters the differences in cut-off marks, wherever possible (like in case of IITs and AIEEE institutes and some States) were used to arrive at individual ranks. Heavily dominated by public institutions, the top-50 listing is a roll call of excellence India’s top 50 engineering institutions 2011.

COMMON INTERVIEW QUESTIONS AND ANSWERS

50 COMMON INTERVIEW QUESTIONS AND ANSWERS

Review these typical interview questions and think about how you would answer them. Read the questions listed; you will also find some strategy suggestions with it.

1. Tell me about yourself:
The most often asked question in interviews. You need to have a short statement prepared in your mind. Be careful that it does not sound rehearsed. Limit it to work-related items unless instructed otherwise. Talk about things you have done and jobs you have held that relate to the position you are interviewing for. Start with the item farthest back and work up to the present.

2. Why did you leave your last job?
Stay positive regardless of the circumstances. Never refer to a major problem with
management and never speak ill of supervisors, co-workers or the organization. If you do, you will be the one looking bad. Keep smiling and talk about leaving for a positive reason such as an opportunity, a chance to do something special or other forward-looking reasons.

3. What experience do you have in this field?
Speak about specifics that relate to the position you are applying for. If you do not have specific experience, get as close as you can.

4. Do you consider yourself successful?
You should always answer yes and briefly explain why. A good explanation is that you have set goals, and you have met some and are on track to achieve the others.

5. What do co-workers say about you?
Be prepared with a quote or two from co-workers. Either a specific statement or a
paraphrase will work. Jill Clark, a co-worker at Smith Company, always said I was the hardest workers she had ever known. It is as powerful as Jill having said it at the interview herself.

6. What do you know about this organization?
This question is one reason to do some research on the organization before the interview. Find out where they have been and where they are going. What are the current issues and who are the major players?

7. What have you done to improve your knowledge in the last year?
Try to include improvement activities that relate to the job. A wide variety of activities can be mentioned as positive self-improvement. Have some good ones handy to mention.

8. Are you applying for other jobs?
Be honest but do not spend a lot of time in this area. Keep the focus on this job and what you can do for this organization. Anything else is a distraction.

9. Why do you want to work for this organization?
This may take some thought and certainly, should be based on the research you have done on the organization. Sincerity is extremely important here and will easily be sensed. Relate it to your long-term career goals.

10. Do you know anyone who works for us?
Be aware of the policy on relatives working for the organization. This can affect your answer even though they asked about friends not relatives. Be careful to mention a friend only if they are well thought of.

11. What kind of salary do you need?
A loaded question. A nasty little game that you will probably lose if you answer first. So, do not answer it. Instead, say something like, That's a tough question. Can you tell me the range for this position? In most cases, the interviewer, taken off guard, will tell you. If not, say that it can depend on the details of the job. Then give a wide range.

12. Are you a team player?
You are, of course, a team player. Be sure to have examples ready. Specifics that show you often perform for the good of the team rather than for yourself are good evidence of your team attitude. Do not brag, just say it in a matter-of-fact tone. This is a key point.

13. How long would you expect to work for us if hired?
Specifics here are not good. Something like this should work: I'd like it to be a long time. Or As long as we both feel I'm doing a good job.

14. Have you ever had to fire anyone? How did you feel about that?
This is serious. Do not make light of it or in any way seem like you like to fire people. At the same time, you will do it when it is the right thing to do. When it comes to the organization versus the individual who has created a harmful situation, you will protect the organization. Remember firing is not the same as layoff or reduction in force.

15. What is your philosophy towards work?
The interviewer is not looking for a long or flowery dissertation here. Do you have strong feelings that the job gets done? Yes. That's the type of answer that works best here. Short and positive, showing a benefit to the organization.

16. If you had enough money to retire right now, would you?
Answer yes if you would. But since you need to work, this is the type of work you prefer. Do not say yes if you do not mean it.

17. Have you ever been asked to leave a position?
If you have not, say no. If you have, be honest, brief and avoid saying negative things about the people or organization involved.

18. Explain how you would be an asset to this organization
You should be anxious for this question. It gives you a chance to highlight your best points as they relate to the position being discussed. Give a little advance thought to this relationship.

19. Why should we hire you?
Point out how your assets meet what the organization needs. Do not mention any other
candidates to make a comparison.


20. Tell me about a suggestion you have made
Have a good one ready. Be sure and use a suggestion that was accepted and was then
considered successful. One related to the type of work applied for is a real plus.

21. What irritates you about co-workers?
This is a trap question. Think real hard but fail to come up with anything that irritates you. A short statement that you seem to get along with folks is great.

22. What is your greatest strength?
Numerous answers are good, just stay positive. A few good examples:
Your ability to prioritize, Your problem-solving skills, Your ability to work under pressure, Your ability to focus on projects, Your professional expertise, Your leadership skills, Your positive attitude .

23. Tell me about your dream job.
Stay away from a specific job. You cannot win. If you say the job you are contending for is it, you strain credibility. If you say another job is it, you plant the suspicion that you will be dissatisfied with this position if hired. The best is to stay genetic and say something like: A job where I love the work, like the people, can contribute and can't wait to get to work.

24. Why do you think you would do well at this job?
Give several reasons and include skills, experience and interest.

25. What are you looking for in a job?
See answer # 23

26. What kind of person would you refuse to work with?
Do not be trivial. It would take disloyalty to the organization, violence or lawbreaking to get you to object. Minor objections will label you as a whiner.

27. What is more important to you: the money or the work?
Money is always important, but the work is the most important. There is no better answer.

28. What would your previous supervisor say your strongest point is?
There are numerous good possibilities:
Loyalty, Energy, Positive attitude, Leadership, Team player, Expertise, Initiative, Patience, Hard work, Creativity, Problem solver

29. Tell me about a problem you had with a supervisor
Biggest trap of all. This is a test to see if you will speak ill of your boss. If you fall for it and tell about a problem with a former boss, you may well below the interview right there. Stay positive and develop a poor memory about any trouble with a supervisor.

30. What has disappointed you about a job?
Don't get trivial or negative. Safe areas are few but can include:
Not enough of a challenge. You were laid off in a reduction Company did not win a contract, which would have given you more responsibility.

31. Tell me about your ability to work under pressure.
You may say that you thrive under certain types of pressure. Give an example that relates to the type of position applied for.

32. Do your skills match this job or another job more closely?
Probably this one. Do not give fuel to the suspicion that you may want another job more than this one.

33. What motivates you to do your best on the job?
This is a personal trait that only you can say, but good examples are:
Challenge, Achievement, Recognition

34. Are you willing to work overtime? Nights? Weekends?
This is up to you. Be totally honest.

35. How would you know you were successful on this job?
Several ways are good measures:
You set high standards for yourself and meet them. Your outcomes are a success.Your boss tell you that you are successful

36. Would you be willing to relocate if required?
You should be clear on this with your family prior to the interview if you think there is a chance it may come up. Do not say yes just to get the job if the real answer is no. This can create a lot of problems later on in your career. Be honest at this point and save yourself future grief.

37. Are you willing to put the interests of the organization ahead of your own?
This is a straight loyalty and dedication question. Do not worry about the deep ethical and philosophical implications. Just say yes.

38. Describe your management style.
Try to avoid labels. Some of the more common labels, like progressive, salesman or
consensus, can have several meanings or descriptions depending on which management
expert you listen to. The situational style is safe, because it says you will manage according to the situation, instead of one size fits all.

39. What have you learned from mistakes on the job?
Here you have to come up with something or you strain credibility. Make it small, well intentioned mistake with a positive lesson learned. An example would be working too far ahead of colleagues on a project and thus throwing coordination off.

40. Do you have any blind spots?
Trick question. If you know about blind spots, they are no longer blind spots. Do not reveal any personal areas of concern here. Let them do their own discovery on your bad points. Do not hand it to them.

41. If you were hiring a person for this job, what would you look for?
Be careful to mention traits that are needed and that you have.

42. Do you think you are overqualified for this position?
Regardless of your qualifications, state that you are very well qualified for the position.

43. How do you propose to compensate for your lack of experience?
First, if you have experience that the interviewer does not know about, bring that up: Then, point out (if true) that you are a hard working quick learner.

44. What qualities do you look for in a boss?
Be generic and positive. Safe qualities are knowledgeable, a sense of humor, fair, loyal to subordinates and holder of high standards. All bosses think they have these traits.

45. Tell me about a time when you helped resolve a dispute between others.
Pick a specific incident. Concentrate on your problem solving technique and not the dispute you settled.

46. What position do you prefer on a team working on a project?
Be honest. If you are comfortable in different roles, point that out.

47. Describe your work ethic.
Emphasize benefits to the organization. Things like, determination to get the job done and work hard but enjoy your work are good.

48. What has been your biggest professional disappointment?
Be sure that you refer to something that was beyond your control. Show acceptance and no negative feelings.

49. Tell me about the most fun you have had on the job.
Talk about having fun by accomplishing something for the organization.

50. Do you have any questions for me?
Always have some questions prepared. Questions prepared where you will be an asset to the organization are good. How soon will I be able to be productive? and What type of projects will I be able to assist on? are examples.

C++ Interview Questions and Answers (4)

C++ Interview Questions and Answers (4)

Pointers

Q: What is a dangling pointer?
A: A dangling pointer arises when you use the address of an object after its lifetime is over. This may occur in situations like returning addresses of the automatic variables from a function or using the address of the memory block after it is freed.

Q: What is Memory Leak?
A: Memory which has no pointer pointing to it and there is no way to delete or reuse this memory(object), it causes Memory leak.
{
Base *b = new base();
}
Out of this scope b no longer exists, but the memory it was pointing to was not deleted. Pointer b
itself was destroyed when it went out of scope.

Q: What is auto pointer?
A: The simplest example of a smart pointer is auto_ptr, which is included in the standard C++
library. Auto Pointer only takes care of Memory leak and does nothing about dangling pointers
issue. You can find it in the header . Here is part of auto_ptr's implementation, to illustrate what
it does:


template class auto_ptr
{
T* ptr;
public:
explicit auto_ptr(T* p = 0) : ptr(p) {}
~auto_ptr() {delete ptr;}
T& operator*() {return *ptr;}
T* operator->() {return ptr;}
// ...
};



As you can see, auto_ptr is a simple wrapper around a regular pointer. It forwards all meaningful
operations to this pointer (dereferencing and indirection). Its smartness in the destructor: the
destructor takes care of deleting the pointer.
For the user of auto_ptr, this means that instead of writing:


void foo()
{
MyClass* p(new MyClass);
p->DoSomething();

delete p;
}


You can write:
void foo()
{
auto_ptr p(new MyClass);
p->DoSomething();
}

And trust p to cleanup after itself.
Q: What issue do auto_ptr objects address?
A: If you use auto_ptr objects you would not have to be concerned with heap objects not being
deleted even if the exception is thrown.
Q: What is a smart pointer?
A: A smart pointer is a C++ class that mimics a regular pointer in syntax and some semantics,
but it does more. Because smart pointers to different types of objects tend to have a lot of code in
common, almost all good-quality smart pointers in existence are templated by the pointee type,
as you can see in the following code:


template
class SmartPtr
{
public:
explicit SmartPtr(T* pointee) : pointee_(pointee);
SmartPtr& operator=(const SmartPtr& other);
~SmartPtr();
T& operator*() const
{
...
return *pointee_;
}
T* operator->() const
{
...
return pointee_;
}
private:
T* pointee_;
...
};


SmartPtr aggregates a pointer to T in its member variable pointee_. That's what most smart
pointers do. In some cases, a smart pointer might aggregate some handles to data and compute
the pointer on the fly.
The two operators give SmartPtr pointer-like syntax and semantics. That is, you can write


class Widget
{
public:
void Fun();
};

SmartPtr sp(new Widget);
sp->Fun();
(*sp).Fun();



Aside from the definition of sp, nothing reveals it as not being a pointer. This is the mantra of
smart pointers: You can replace pointer definitions with smart pointer definitions without
incurring major changes to your application's code. You thus get extra goodies with ease.
Minimizing code changes is very appealing and vital for getting large applications to use smart
pointers. As you will soon see, however, smart pointers are not a free lunch.

Q: Is there any problem with the following : char*a=NULL; char& p = *a;?
A: The result is undefined. You should never do this. A reference must always refer to some
object.

Q: What is the difference between a pointer and a reference?
A: A reference must always refer to some object and, therefore, must always be initialized;
pointers do not have such restrictions. A pointer can be reassigned to point to different objects
while a reference always refers to an object with which it was initialized.

Q: What is the difference between const char *myPointer and char *const myPointer?
A: Const char *myPointer is a non constant pointer to constant data; while char *const
myPointer is a constant pointer to non constant data.

Q:When should I use references, and when should I use pointers?
A: Use references when you can, and pointers when you have to.

References are usually preferred over pointers whenever you don't need "reseating". This usually
means that references are most useful in a class's public interface. References typically appear on
the skin of an object, and pointers on the inside.

The exception to the above is where a function's parameter or return value needs a "sentinel"
reference a reference that does not refer to an object. This is usually best done by

returning/taking a pointer, and giving the NULL pointer this special significance (references
should always alias objects, not a dereferenced NULL pointer).

Note: Old line C programmers sometimes don't like references since they provide reference
semantics that isn't explicit in the caller's code. After some C++ experience, however, one
quickly realizes this is a form of information hiding, which is an asset rather than a liability. E.g.,
programmers should write code in the language of the problem rather than the language of the
machine.

String


Q: What happens if you write this code?

string& foo()
{
return "Hello World";
}

cout << foo() << endl; A: 1. Will give an error since Hello World is created as a unnamed character pointer to const. it is being assigned to non-const reference which is not allowed. could not convert `"Hello World"' to `std::string&' 2. const string& foo1() { return "Hello World"; } Gives a warning, since you are returning a reference to temporary, which will die immediately when the expression is completed. classsize.C:7: warning: returning reference to temporary output : Aborted. Segment fault. 3. Char *foo1() { return “Hello World”; } Returning the address of character literal which is created on the static memory. In C++, the compiler allows the use of string literals to initialize character arrays. A string literal consists of zero or more characters surrounded by double quotation marks ("). A string literal represents a sequence of characters that, taken together, form a null-terminated string. The compiler creates static storage space for the string, null-terminates it, and puts the address of this space into the char* variable. The type of a literal string is an array of const chars. char* szMyString = "Hello world."; szMyString[3] = 'q'; // undefined, modifying static buffer!!! In the following example, the compiler automatically puts a null-character at the end of the literal string of characters "Hello world". It then creates a storage space for the resulting string - this is an array of const chars. Then it puts the starting address of this array into the szMyString variable. We will try to modify this string (wherever it is stored) by accessing it via an index into szMyString. This is a Bad Thing; the standard does not say where the compiler puts literal strings. They can go anywhere, possibly in some place in memory that you shouldn't be modifying. Q: How do I convert an integer to a string? A: The simplest way is to use a stringstream: #include #include #include using namespace std; string itos(int i) // convert int to string { stringstream s; s << i; return s.str(); } int main() { int i = 127; string ss = itos(i); const char* p = ss.c_str(); cout << ss << " " << p << "\n"; } Naturally, this technique works for converting any type that you can output using << to a string. C vs C++ Q: How do you link a C++ program to C functions? A: By using the extern "C" linkage specification around the C function declarations. Programmers should know about mangled function names and type-safe linkages. Then they should explain how the extern "C" linkage specification statement turns that feature off during compilation so that the linker properly links function calls to C functions. Q: Is there anything you can do in C++ that you cannot do in C? A: No. There is nothing you can do in C++ that you cannot do in C. After all you can write a C++ compiler in C Q: What are the differences between a struct in C and in C++? A: In C++ a struct is similar to a class except for the default access specifier( refere to other question in the document). In C we have to include the struct keyword when declaring struct. In c++ we don’t have to. Q: What does extern "C" int func(int *, Foo) accomplish? A: It will turn o_ "name mangling" for func so that one can link to code compiled by a C compiler. Q: What are the access privileges in C++? What is the default access level? A: The access privileges in C++ are private, public and protected. The default access level assigned to members of a class is private. Private members of a class are accessible only within the class and by friends of the class. Protected members are accessible by the class itself and it's sub-classes. Public members of a class can be accessed by anyone. Q:How does C++ help with the tradeoff of safety vs. usability? A: In C, encapsulation was accomplished by making things static in a compilation unit or module. This prevented another module from accessing the static stuff. (By the way, static data at file-scope is now deprecated in C++: don't do that.) Unfortunately this approach doesn't support multiple instances of the data, since there is no direct support for making multiple instances of a module's static data. If multiple instances were needed in C, programmers typically used a struct. But unfortunately C structs don't support encapsulation. This exacerbates the tradeoff between safety (information hiding) and usability (multiple instances). In C++, you can have both multiple instances and encapsulation via a class. The public part of a class contains the class's interface, which normally consists of the class's public member functions and its friend functions. The private and/or protected parts of a class contain the class's implementation, which is typically where the data lives. The end result is like an "encapsulated struct." This reduces the tradeoff between safety (information hiding) and usability (multiple instances). Overloading operator Q: Name the operators that cannot be overloaded? A:sizeof, ., .*, .->, ::, ?:

Q: What is overloading??
A: With the C++ language, you can overload functions and operators. Overloading is the
practice of supplying more than one definition for a given function name in the same scope.
- Any two functions in a set of overloaded functions must have different argument lists.
- Overloading functions with argument lists of the same types, based on return type alone, is an
error.

Q: How are prefix and postfix versions of operator++() differentiated?
A: The postfix version of operator++() has a dummy parameter of type int. The prefix version
does not have dummy parameter.

Q: Can you overload a function based only on whether a parameter is a value or a reference?
A: No. Passing by value and by reference looks identical to the caller.
Q: What's the deal with operator overloading?
A: It allows you to provide an intuitive interface to users of your class, plus makes it possible for
templates to work equally well with classes and built-in/intrinsic types.

Operator overloading allows C/C++ operators to have user-defined meanings on user-defined
types (classes). Overloaded operators are syntactic sugar for function calls:


class Fred {
public:
...
};

#if 0

// Without operator overloading:
Fred add(const Fred& x, const Fred& y);
Fred mul(const Fred& x, const Fred& y);

Fred f(const Fred& a, const Fred& b, const Fred& c)
{
return add(add(mul(a,b), mul(b,c)), mul(c,a)); // Yuk...
}

#else

// With operator overloading:

Fred operator+ (const Fred& x, const Fred& y);
Fred operator* (const Fred& x, const Fred& y);

Fred f(const Fred& a, const Fred& b, const Fred& c)
{
return a*b + b*c + c*a;
}

#endif

Q: What are the benefits of operator overloading?
A: By overloading standard operators on a class, you can exploit the intuition of the users of that
class. This lets users program in the language of the problem domain rather than in the language
of the machine.

The ultimate goal is to reduce both the learning curve and the defect rate.

Q: What are some examples of operator overloading?
A: Here are a few of the many examples of operator overloading:

myString + yourString might concatenate two std::string objects
myDate++ might increment a Date object
a * b might multiply two Number objects
a[i] might access an element of an Array object
x = *p might dereference a "smart pointer" that "points" to a disk record it could seek to the
location on disk where p "points" and return the appropriate record into x

Q: But operator overloading makes my class look ugly; isn't it supposed to make my code
clearer?
A: Operator overloading makes life easier for the users of a class, not for the developer of the
class!

Consider the following example.


class Array {
public:
int& operator[] (unsigned i); // Some people don't like this syntax
...
};

inline
int& Array::operator[] (unsigned i) // Some people don't like this syntax
{
...
}

Some people don't like the keyword operator or the somewhat funny syntax that goes with it in
the body of the class itself. But the operator overloading syntax isn't supposed to make life easier
for the developer of a class. It's supposed to make life easier for the users of the class:


int main()
{
Array a;
a[3] = 4; // User code should be obvious and easy to understand...
...
}
Remember: in a reuse-oriented world, there will usually be many people who use your class, but
there is only one person who builds it (yourself); therefore you should do things that favor the
many rather than the few.

Q: What operators can/cannot be overloaded?
A: Most can be overloaded. The only C operators that can't be are . and ?: (and sizeof, which is
technically an operator). C++ adds a few of its own operators, most of which can be overloaded
except :: and .*.

Here's an example of the subscript operator (it returns a reference). First without operator
overloading:


class Array {
public:
int& elem(unsigned i) { if (i > 99) error(); return data[i]; }
private:
int data[100];
};

int main()
{
Array a;
a.elem(10) = 42;
a.elem(12) += a.elem(13);
...
}
Now the same logic is presented with operator overloading:


class Array {
public:
int& operator[] (unsigned i) { if (i > 99) error(); return data[i]; }
private:
int data[100];

};

int main()
{
Array a;
a[10] = 42;
a[12] += a[13];
...
}

Q: Can I overload operator== so it lets me compare two char[] using a string comparison?
A: No: at least one operand of any overloaded operator must be of some user-defined type (most
of the time that means a class).

But even if C++ allowed you to do this, which it doesn't, you wouldn't want to do it anyway
since you really should be using a std::string-like class rather than an array of char in the first
place since arrays are evil.

Q: Can I create a operator** for "to-the-power-of" operations?
A: Nope.

The names of, precedence of, associativity of, and arity of operators is fixed by the language.
There is no operator** in C++, so you cannot create one for a class type.

If you're in doubt, consider that x ** y is the same as x * (*y) (in other words, the compiler
assumes y is a pointer). Besides, operator overloading is just syntactic sugar for function calls.
Although this particular syntactic sugar can be very sweet, it doesn't add anything fundamental. I
suggest you overload pow(base,exponent) (a double precision version is in ).

By the way, operator^ can work for to-the-power-of, except it has the wrong precedence and
associativity.

Q: Okay, that tells me the operators I can override; which operators should I override?
A: Bottom line: don't confuse your users.

Remember the purpose of operator overloading: to reduce the cost and defect rate in code that
uses your class. If you create operators that confuse your users (because they're cool, because
they make the code faster, because you need to prove to yourself that you can do it; doesn't really
matter why), you've violated the whole reason for using operator overloading in the first place.

Q: What are some guidelines / "rules of thumb" for overloading operators?
A: Here are a few guidelines / rules of thumb (but be sure to read the previous FAQ before
reading this list):

Use common sense. If your overloaded operator makes life easier and safer for your users, do it;
otherwise don't. This is the most important guideline. In fact it is, in a very real sense, the only

guideline; the rest are just special cases.
If you define arithmetic operators, maintain the usual arithmetic identities. For example, if your
class defines x + y and x - y, then x + y - y ought to return an object that is behaviorally
equivalent to x. The term behaviorally equivalent is defined in the bullet on x == y below, but
simply put, it means the two objects should ideally act like they have the same state. This should
be true even if you decide not to define an == operator for objects of your class.
You should provide arithmetic operators only when they make logical sense to users. Subtracting
two dates makes sense, logically returning the duration between those dates, so you might want
to allow date1 - date2 for objects of your Date class (provided you have a reasonable class/type
to represent the duration between two Date objects). However adding two dates makes no sense:
what does it mean to add July 4, 1776 to June 5, 1959? Similarly it makes no sense to multiply or
divide dates, so you should not define any of those operators.
You should provide mixed-mode arithmetic operators only when they make logical sense to
users. For example, it makes sense to add a duration (say 35 days) to a date (say July 4, 1776), so
you might define date + duration to return a Date. Similarly date - duration could also return a
Date. But duration - date does not make sense at the conceptual level (what does it mean to
subtract July 4, 1776 from 35 days?) so you should not define that operator.
If you provide constructive operators, they should return their result by value. For example, x + y
should return its result by value. If it returns by reference, you will probably run into lots of
problems figuring out who owns the referent and when the referent will get destructed. Doesn't
matter if returning by reference is more efficient; it is probably wrong. See the next bullet for
more on this point.
If you provide constructive operators, they should not change their operands. For example, x + y
should not change x. For some crazy reason, programmers often define x + y to be logically the
same as x += y because the latter is faster. But remember, your users expect x + y to make a
copy. In fact they selected the + operator (over, say, the += operator) precisely because they
wanted a copy. If they wanted to modify x, they would have used whatever is equivalent to x +=
y instead. Don't make semantic decisions for your users; it's their decision, not yours, whether
they want the semantics of x + y vs. x += y. Tell them that one is faster if you want, but then step
back and let them make the final decision they know what they're trying to achieve and you do
not.
If you provide constructive operators, they should allow promotion of the left-hand operand. For
example, if your class Fraction supports promotion from int to Fraction (via the non-explicit ctor
Fraction::Fraction(int)), and if you allow x - y for two Fraction objects, you should also allow 42
- y. In practice that simply means that your operator-() should not be a member function of
Fraction. Typically you will make it a friend, if for no other reason than to force it into the
public: part of the class, but even if it is not a friend, it should not be a member.
In general, your operator should change its operand(s) if and only if the operands get changed
when you apply the same operator to intrinsic types. x == y and x << y should not change either operand; x *= y and x <<= y should (but only the left-hand operand). If you define x++ and ++x, maintain the usual identities. For example, x++ and ++x should have should have the same observable effect on x, and should differ only in what they return. ++x should return x by reference; x++ should either return a copy (by value) of the original state of x or should have a void return-type. You're usually better off returning a copy of the original state of x by value, especially if your class will be used in generic algorithms. The easy way to do that is to implement x++ using three lines: make a local copy of *this, call ++x (i.e., this- >operator++()), then return the local copy. Similar comments for x-- and --x.
If you define ++x and x += 1, maintain the usual identities. For example, these expressions
should have the same observable behavior, including the same result. Among other things, that
means your += operator should return x by reference. Similar comments for --x and x -= 1.
If you define *p and p[0] for pointer-like objects, maintain the usual identities. For example,
these two expressions should have the same result and neither should change p.
If you define p[i] and *(p+i) for pointer-like objects, maintain the usual identities. For example,
these two expressions should have the same result and neither should change p. Similar
comments for p[-i] and *(p-i).
Subscript operators generally come in pairs; see on const-overloading.
If you define x == y, then x == y should be true if and only if the two objects are behaviorally
equivalent. In this bullet, the term "behaviorally equivalent" means the observable behavior of
any operation or sequence of operations applied to x will be the same as when applied to y. The
term "operation" means methods, friends, operators, or just about anything else you can do with
these objects (except, of course, the address-of operator). You won't always be able to achieve
that goal, but you ought to get close, and you ought to document any variances (other than the
address-of operator).
If you define x == y and x = y, maintain the usual identities. For example, after an assignment,
the two objects should be equal. Even if you don't define x == y, the two objects should be
behaviorally equivalent (see above for the meaning of that phrase) after an assignment.
If you define x == y and x != y, you should maintain the usual identities. For example, these
expressions should return something convertible to bool, neither should change its operands, and
x == y should have the same result as !(x != y), and vice versa.
If you define inequality operators like x <= y and x < y, you should maintain the usual identities. For example, if x < y and y < z are both true, then x < z should also be true, etc. Similar comments for x >= y and x > y.
If you define inequality operators like x < y and x >= y, you should maintain the usual identities.
For example, x < y should have the result as !(x >= y). You can't always do that, but you should
get close and you should document any variances. Similar comments for x > y and !(x <= y), etc.
Avoid overloading short-circuiting operators: x || y or x && y. The overloaded versions of these
do not short-circuit they evaluate both operands even if the left-hand operand "determines" the
outcome, so that confuses users.
Avoid overloading the comma operator: x, y. The overloaded comma operator does not have the
same ordering properties that it has when it is not overloaded, and that confuses users.
Don't overload an operator that is non-intuitive to your users. This is called the Doctrine of Least
Surprise. For example, altough C++ uses std::cout << x for printing, and although printing is
techincally called inserting, and although inserting sort of sounds like what happens when you
push an element onto a stack, don't overload myStack << x to push an element onto a stack. It
might make sense when you're really tired or otherwise mentally impaired, and a few of your
friends might think it's "kewl," but just say No.
Use common sense. If you don't see "your" operator listed here, you can figure it out. Just
remember the ultimate goals of operator overloading: to make life easier for your users, in
particular to make their code cheaper to write and more obvious.
Caveat: the list is not exhaustive. That means there are other entries that you might consider
"missing." I know.

C++ Interview Questions and Answers (3)

C++ Interview Questions and Answers (3)

virtual

Q: What is virtual function?
A: When derived class overrides the base class method by redefining the same function, then if
client wants to access redefined the method from derived class through a pointer from base class
object, then you must define this function in base class as virtual function.
class parent
{
void Show()
{
cout << "i'm parent" << endl; } }; class child: public parent { void Show() { cout << "i'm child" << endl; } }; parent * parent_object_ptr = new child; parent_object_ptr->show() // calls parent->show()
now we goto virtual world...
class parent
{
virtual void Show()
{
cout << "i'm parent" << endl; } }; class child: public parent { void Show() { cout << "i'm child" << endl; } }; parent * parent_object_ptr = new child; parent_object_ptr->show() // calls child->show()

Q: What is a "pure virtual" member function?
A: The abstract class whose pure virtual method has to be implemented by all the classes which
derive on these. Otherwise it would result in a compilation error. This construct should be used
when one wants to ensure that all the derived classes implement the method defined as pure
virtual in base class.

Q: How virtual functions are implemented C++?
A: Virtual functions are implemented using a table of function pointers, called the vtable. There
is one entry in the table per virtual function in the class. This table is created by the constructor
of the class. When a derived class is constructed, its base class is constructed _rst which creates
the vtable. If the derived class overrides any of the base classes virtual functions, those entries in
the vtable are overwritten by the derived class constructor. This is why you should never call
virtual functions from a constructor: because the vtable entries for the object may not have
been set up by the derived class constructor yet, so you might end up calling base class
implementations of those virtual functions


Q: What is pure virtual function? or what is abstract class?
A: When you de_ne only function prototype in a base class without implementation and do the
complete implementation in derived class. This base class is called abstract class and client won't
able to instantiate an object using this base class. You can make a pure virtual function or
abstract class this way..
class Boo
{
void foo() = 0;
}
Boo MyBoo; // compilation error

Q: What is Pure Virtual Function? Why and when it is used?
A: The abstract class whose pure virtual method has to be implemented by all the classes which
derive on these. Otherwise it would result in a compilation error. This construct should be used
when one wants to ensure that all the derived classes implement the method defined as pure
virtual in base class.

Q: How Virtual functions call up is maintained?
A: Through Look up tables added by the compile to every class image. This also leads to
performance penalty.

Q: What is a virtual destructor?
A: The simple answer is that a virtual destructor is one that is declared with the virtual attribute.
The behavior of a virtual destructor is what is important. If you destroy an object through a caller
or reference to a base class, and the base-class destructor is not virtual, the derived-class
destructors are not executed, and the destruction might not be complete.


Inheritance

Q: What is inheritance?
A: Inheritance allows one class to reuse the state and behavior of another class. The derived class
inherits the properties and method implementations of the base class and extends it by overriding
methods and adding additional properties and methods.

Q: When should you use multiple inheritance?
A:There are three acceptable answers:- "Never,""Rarely," and "When the problem domain
cannot be accurately modeled any other way." Consider an Asset class, Building class, Vehicle
class, and CompanyCar class. All company cars are vehicles. Some company cars are assets
because the organizations own them. Others might be leased. Not all assets are vehicles. Money
accounts are assets. Real estate holdings are assets. Some real estate holdings are buildings. Not
all buildings are assets. Ad infinitum. When you diagram these relationships, it becomes
apparent that multiple inheritance is a likely and intuitive way to model this common problem
domain. The applicant should understand, however, that multiple inheritance, like a chainsaw, is
a useful tool that has its perils, needs respect, and is best avoided except when nothing else will
do.

Q: Explain the ISA and HASA class relationships. How would you implement each in a class
design?
A: A specialized class "is" a specialization of another class and, therefore, has the ISA
relationship with the other class. This relationship is best implemented by embedding an object
of the Salary class in the Employee class.

Q: When is a template a better solution than a base class?
A: When you are designing a generic class to contain or otherwise manage objects of other
types, when the format and behavior of those other types are unimportant to their containment or
management, and particularly when those other types are unknown (thus, the generality) to the
designer of the container or manager class.


Q: What is multiple inheritance(virtual inheritance)? What are its advantages and disadvantages?
A: Multiple Inheritance is the process whereby a child can be derived from more than one parent
class. The advantage of multiple inheritance is that it allows a class to inherit the functionality of
more than one base class thus allowing for modeling of complex relationships.
The disadvantage of multiple inheritance is that it can lead to a lot of confusion(ambiguity)
when two base classes implement a method with the same name.
Q: What a derived class inherits or doesn't inherit?
A: Inherits:

Every data member defined in the parent class (although such members may not always be
accessible in the derived class!)
Every ordinary member function of the parent class (although such members may not always be
accessible in the derived class!)

The same initial data layout as the base class.

Doesn't Inherit :

The base class's constructors and destructor.

The base class's assignment operator.

The base class's friends

polymorphism

Q: What is Polymorphism??
A: Polymorphism allows a client to treat di_erent objects in the same way even if they were
created from di_erent classes and exhibit di_erent behaviors. You can use implementation
inheritance to achieve polymorphism in languages such as C++ and Java. Base class object's
pointer can invoke methods in derived class objects. You can also achieve polymorphism in C++
by function overloading and operator overloading.

Q: What is problem with Runtime type identification?
A: The run time type identification comes at a cost of performance penalty. Compiler maintains
the class.

Q: What is Polymorphism?
A: Polymorphism allows a client to treat different objects in the same way even if they were
created from different classes and exhibit different behaviors. You can use implementation
inheritance to achieve polymorphism in languages such as C++ and Java. Base class object's
pointer can invoke methods in derived class objects. You can also achieve polymorphism in
C++ by function overloading and operator overloading.

Classes


Q: What is a class?
A: A class is an expanded concept of a data structure: instead of holding only data, it can hold
both data and functions.

Q: What are the differences between a C++ struct and C++ class?
A: The default member and base class access specifies are different. This is one of the
commonly misunderstood aspects of C++. Believe it or not, many programmers think that a C++
struct is just like a C struct, while a C++ class has inheritance, access specifes, member
functions, overloaded operators, and so on. Actually, the C++ struct has all the features of the
class. The only differences are that a struct defaults to public member access and public base
class inheritance, and a class defaults to the private access specified and private base-class
inheritance.

Q: How do you know that your class needs a virtual destructor?
A: If your class has at least one virtual function, you should make a destructor for this class
virtual. This will allow you to delete a dynamic object through a caller to a base class object. If
the destructor is non-virtual, then wrong destructor will be invoked during deletion of the
dynamic object.

Q: What is encapsulation?
A: Containing and hiding Information about an object, such as internal data structures and code.
Encapsulation isolates the internal complexity of an object's operation from the rest of the
application. For example, a client component asking for net revenue from a business object need
not know the data's origin.

Q: What is "this" pointer?
A: The this pointer is a pointer accessible only within the member functions of a class, struct, or
union type. It points to the object for which the member function is called. Static member
functions do not have a this pointer. When a nonstatic member function is called for an
object, the address of the object is passed as a hidden argument to the function. For example, the
following function call
myDate.setMonth( 3 );
can be interpreted this way:
setMonth( &myDate, 3 );
The object's address is available from within the member function as the this pointer. It is legal,
though unnecessary, to use the this pointer when referring to members of the class.

Q: What happens when you make call "delete this;"?
A: The code has two built-in pitfalls. First, if it executes in a member function for an extern,
static, or automatic object, the program will probably crash as soon as the delete statement
executes. There is no portable way for an object to tell that it was instantiated on the heap, so the
class cannot assert that its object is properly instantiated. Second, when an object commits
suicide this way, the using program might not know about its demise. As far as the instantiating
program is concerned, the object remains in scope and continues to exist even though the object

did itself in. Subsequent dereferencing of the pointer can and usually does lead to disaster.
You should never do this. Since compiler does not know whether the object was allocated on the
stack or on the heap, "delete this" could cause a disaster.


Q: What is assignment operator?
A: Default assignment operator handles assigning one object to another of the same class.
Member to member copy (shallow copy)

Q: What are all the implicit member functions of the class? Or what are all the functions which
compiler implements for us if we don't define one?
A:
(a) default ctor
(b) copy ctor
(c) assignment operator
(d) default destructor
(e) address operator

Q: What is a container class? What are the types of container classes?
A: A container class is a class that is used to hold objects in memory or external storage. A
container class acts as a generic holder. A container class has a predefined behavior and a well-
known interface. A container class is a supporting class whose purpose is to hide the topology
used for maintaining the list of objects in memory. When a container class contains a group of
mixed objects, the container is called a heterogeneous container; when the container is holding a
group of objects that are all the same, the container is called a homogeneous container.

Q: What is Overriding?
A: To override a method, a subclass of the class that originally declared the method must declare
a method with the same name, return type (or a subclass of that return type), and same parameter
list.
The definition of the method overriding is:
· Must have same method name.
· Must have same data type.
· Must have same argument list.
Overriding a method means that replacing a method functionality in child class. To imply
overriding functionality we need parent and child classes. In the child class you define the same
method signature as one defined in the parent class.

Q: How do you access the static member of a class?
A: ::

Q: What is a nested class? Why can it be useful?
A: A nested class is a class enclosed within the scope of another class. For example:
// Example 1: Nested class
//
class OuterClass

{
class NestedClass
{
// ...
};
// ...
};
Nested classes are useful for organizing code and controlling access and dependencies. Nested
classes obey access rules just like other parts of a class do; so, in Example 1, if NestedClass is
public then any code can name it as OuterClass::NestedClass. Often nested classes contain
private implementation details, and are therefore made private; in Example 1, if NestedClass
is private, then only OuterClass's members and friends can use NestedClass. When you
instantiate as outer class, it won't instantiate inside class.

Q: What is a local class? Why can it be useful?
A: Local class is a class defined within the scope of a function _ any function, whether a
member function or a free function. For example:
// Example 2: Local class
//
int f()
{
class LocalClass
{
// ...
};
// ...
};
Like nested classes, local classes can be a useful tool for managing code dependencies.
Q: What a derived class can add?
A: New data members

New member functions

New constructors and destructor

New friends
Q: What happens when a derived-class object is created and destroyed?
A: Space is allocated (on the stack or the heap) for the full object (that is, enough space to store
the data members inherited from the base class plus the data members defined in the derived
class itself)

The base class's constructor is called to initialize the data members inherited from the base class

The derived class's constructor is then called to initialize the data members added in the derived
class


The derived-class object is then usable

When the object is destroyed (goes out of scope or is deleted) the derived class's destructor is
called on the object first

Then the base class's destructor is called on the object

Finally the allocated space for the full object is reclaimed

Q: How do I create a subscript operator for a Matrix class?
A: Use operator() rather than operator[].

When you have multiple subscripts, the cleanest way to do it is with operator() rather than with
operator[]. The reason is that operator[] always takes exactly one parameter, but operator() can
take any number of parameters (in the case of a rectangular matrix, two parameters are needed).

For example:


class Matrix {
public:
Matrix(unsigned rows, unsigned cols);
double& operator() (unsigned row, unsigned col); subscript operators often come in pairs
double operator() (unsigned row, unsigned col) const; subscript operators often come in pairs
...
~Matrix(); // Destructor
Matrix(const Matrix& m); // Copy constructor
Matrix& operator= (const Matrix& m); // Assignment operator
...
private:
unsigned rows_, cols_;
double* data_;
};

inline
Matrix::Matrix(unsigned rows, unsigned cols)
: rows_ (rows)
, cols_ (cols)
//data_ <--initialized below (after the 'if/throw' statement) { if (rows == 0 || cols == 0) throw BadIndex("Matrix constructor has 0 size"); data_ = new double[rows * cols]; } inline Matrix::~Matrix() { delete[] data_; } inline double& Matrix::operator() (unsigned row, unsigned col) { if (row >= rows_ || col >= cols_)
throw BadIndex("Matrix subscript out of bounds");
return data_[cols_*row + col];
}

inline
double Matrix::operator() (unsigned row, unsigned col) const
{
if (row >= rows_ || col >= cols_)
throw BadIndex("const Matrix subscript out of bounds");
return data_[cols_*row + col];
}
Then you can access an element of Matrix m using m(i,j) rather than m[i][j]:


int main()
{
Matrix m(10,10);
m(5,8) = 106.15;
std::cout << m(5,8); ... } Q: Why shouldn't my Matrix class's interface look like an array-of-array? A: Here's what this FAQ is really all about: Some people build a Matrix class that has an operator[] that returns a reference to an Array object (or perhaps to a raw array, shudder), and that Array object has an operator[] that returns an element of the Matrix (e.g., a reference to a double). Thus they access elements of the matrix using syntax like m[i][j] rather than syntax like m(i,j). The array-of-array solution obviously works, but it is less flexible than the operator() approach. Specifically, there are easy performance tuning tricks that can be done with the operator() approach that are more difficult in the [][] approach, and therefore the [][] approach is more likely to lead to bad performance, at least in some cases. For example, the easiest way to implement the [][] approach is to use a physical layout of the matrix as a dense matrix that is stored in row-major form (or is it column-major; I can't ever remember). In contrast, the operator() approach totally hides the physical layout of the matrix, and that can lead to better performance in some cases. Put it this way: the operator() approach is never worse than, and sometimes better than, the [][] approach. The operator() approach is never worse because it is easy to implement the dense, row-major physical layout using the operator() approach, so when that configuration happens to be the optimal layout from a performance standpoint, the operator() approach is just as easy as the [][] approach (perhaps the operator() approach is a tiny bit easier, but I won't quibble over minor nits). The operator() approach is sometimes better because whenever the optimal layout for a given application happens to be something other than dense, row-major, the implementation is often significantly easier using the operator() approach compared to the [][] approach. As an example of when a physical layout makes a significant difference, a recent project happened to access the matrix elements in columns (that is, the algorithm accesses all the elements in one column, then the elements in another, etc.), and if the physical layout is row- major, the accesses can "stride the cache". For example, if the rows happen to be almost as big as the processor's cache size, the machine can end up with a "cache miss" for almost every element access. In this particular project, we got a 20% improvement in performance by changing the mapping from the logical layout (row,column) to the physical layout (column,row). Of course there are many examples of this sort of thing from numerical methods, and sparse matrices are a whole other dimension on this issue. Since it is, in general, easier to implement a sparse matrix or swap row/column ordering using the operator() approach, the operator() approach loses nothing and may gain something it has no down-side and a potential up-side. Use the operator() approach. Q: Should I design my classes from the outside (interfaces first) or from the inside (data first)? A: From the outside! A good interface provides a simplified view that is expressed in the vocabulary of a user. In the case of OO software, the interface is normally the set of public methods of either a single class or a tight group of classes. First think about what the object logically represents, not how you intend to physically build it. For example, suppose you have a Stack class that will be built by containing a LinkedList: class Stack { public: ... private: LinkedList list_; }; Should the Stack have a get() method that returns the LinkedList? Or a set() method that takes a LinkedList? Or a constructor that takes a LinkedList? Obviously the answer is No, since you should design your interfaces from the outside-in. I.e., users of Stack objects don't care about LinkedLists; they care about pushing and popping. Now for another example that is a bit more subtle. Suppose class LinkedList is built using a linked list of Node objects, where each Node object has a pointer to the next Node: class Node { /*...*/ }; class LinkedList { public: ... private: Node* first_; }; Should the LinkedList class have a get() method that will let users access the first Node? Should the Node object have a get() method that will let users follow that Node to the next Node in the chain? In other words, what should a LinkedList look like from the outside? Is a LinkedList really a chain of Node objects? Or is that just an implementation detail? And if it is just an implementation detail, how will the LinkedList let users access each of the elements in the LinkedList one at a time? The key insight is the realization that a LinkedList is not a chain of Nodes. That may be how it is built, but that is not what it is. What it is is a sequence of elements. Therefore the LinkedList abstraction should provide a LinkedListIterator class as well, and that LinkedListIterator might have an operator++ to go to the next element, and it might have a get()/set() pair to access its value stored in the Node (the value in the Node element is solely the responsibility of the LinkedList user, which is why there is a get()/set() pair that allows the user to freely manipulate that value). Starting from the user's perspective, we might want our LinkedList class to support operations that look similar to accessing an array using pointer arithmetic: void userCode(LinkedList& a) { for (LinkedListIterator p = a.begin(); p != a.end(); ++p) std::cout << *p << '\n'; } To implement this interface, LinkedList will need a begin() method and an end() method. These return a LinkedListIterator object. The LinkedListIterator will need a method to go forward, ++p; a method to access the current element, *p; and a comparison operator, p != a.end(). The code follows. The important thing to notice is that LinkedList does not have any methods that let users access Nodes. Nodes are an implementation technique that is completely buried. This makes the LinkedList class safer (no chance a user will mess up the invariants and linkages between the various nodes), easier to use (users don't need to expend extra effort keeping the node-count equal to the actual number of nodes, or any other infrastructure stuff), and more flexible (by changing a single typedef, users could change their code from using LinkedList to some other list-like class and the bulk of their code would compile cleanly and hopefully with improved performance characteristics). #include // Poor man's exception handling class LinkedListIterator; class LinkedList; class Node { // No public members; this is a "private class" friend class LinkedListIterator; // A friend class friend class LinkedList; Node* next_; int elem_; }; class LinkedListIterator { public: bool operator== (LinkedListIterator i) const; bool operator!= (LinkedListIterator i) const; void operator++ (); // Go to the next element int& operator* (); // Access the current element private: LinkedListIterator(Node* p); Node* p_; friend class LinkedList; // so LinkedList can construct a LinkedListIterator }; class LinkedList { public: void append(int elem); // Adds elem after the end void prepend(int elem); // Adds elem before the beginning ... LinkedListIterator begin(); LinkedListIterator end(); ... private: Node* first_; }; Here are the methods that are obviously inlinable (probably in the same header file): inline bool LinkedListIterator::operator== (LinkedListIterator i) const { return p_ == i.p_; } inline bool LinkedListIterator::operator!= (LinkedListIterator i) const { return p_ != i.p_; } inline void LinkedListIterator::operator++() { assert(p_ != NULL); // or if (p_==NULL) throw ... p_ = p_->next_;
}

inline int& LinkedListIterator::operator*()
{
assert(p_ != NULL); // or if (p_==NULL) throw ...
return p_->elem_;
}

inline LinkedListIterator::LinkedListIterator(Node* p)
: p_(p)
{ }

inline LinkedListIterator LinkedList::begin()
{
return first_;
}

inline LinkedListIterator LinkedList::end()
{
return NULL;
}
Conclusion: The linked list had two different kinds of data. The values of the elements stored in
the linked list are the responsibility of the user of the linked list (and only the user; the linked list
itself makes no attempt to prohibit users from changing the third element to 5), and the linked
list's infrastructure data (next pointers, etc.), whose values are the responsibility of the linked list
(and only the linked list; e.g., the linked list does not let users change (or even look at!) the
various next pointers).

Thus the only get()/set() methods were to get and set the elements of the linked list, but not the
infrastructure of the linked list. Since the linked list hides the infrastructure pointers/etc., it is

able to make very strong promises regarding that infrastructure (e.g., if it were a doubly linked
list, it might guarantee that every forward pointer was matched by a backwards pointer from the
next Node).

So, we see here an example of where the values of some of a class's data is the responsibility of
users (in which case the class needs to have get()/set() methods for that data) but the data that the
class wants to control does not necessarily have get()/set() methods.

Note: the purpose of this example is not to show you how to write a linked-list class. In fact you
should not "roll your own" linked-list class since you should use one of the "container classes"
provided with your compiler. Ideally you'll use one of the standard container classes such as the
std::list template.

C++ Interview Questions and Answers (2)

C++ Interview Questions and Answers (2)

Q: When I write a derived class's destructor, do I need to explicitly call the destructor for my base class?
A: No. You never need to explicitly call a destructor (except with placement new).

A derived class's destructor (whether or not you explicitly define one) automagically invokes the destructors for base class subobjects. Base classes are destructed after member objects. In the event of multiple inheritance, direct base classes are destructed in the reverse order of their appearance in the inheritance list.


class Member {
public:
~Member();
...
};

class Base {
public:
virtual ~Base(); // A virtual destructor
...
};

class Derived : public Base {
public:
~Derived();
...
private:
Member x_;
};

Derived::~Derived()
{
// Compiler automagically calls x_.~Member()
// Compiler automagically calls Base::~Base()
}
Note: Order dependencies with virtual inheritance are trickier. If you are relying on order dependencies in a virtual inheritance hierarchy, you'll need a lot more information than is in this

FAQ.
Q: Is there any difference between List x; and List x();?
A: A big difference!

Suppose that List is the name of some class. Then function f() declares a local List object called
x:


void f()
{
List x; // Local object named x (of class List)
...
}
But function g() declares a function called x() that returns a List:


void g()
{
List x(); // Function named x (that returns a List)
...
}

Q: Can one constructor of a class call another constructor of the same class to initialize the this
object?
A: Nope.

Let's work an example. Suppose you want your constructor Foo::Foo(char) to call another constructor of the same class, say Foo::Foo(char,int), in order that Foo::Foo(char,int) would help initialize the this object. Unfortunately there's no way to do this in C++.

Some people do it anyway. Unfortunately it doesn't do what they want. For example, the line Foo(x, 0); does not call Foo::Foo(char,int) on the this object. Instead it calls Foo::Foo(char,int) to initialize a temporary, local object (not this), then it immediately destructs that temporary when control flows over the ;.

class Foo {
public:
Foo(char x);
Foo(char x, int y);
...
};

Foo::Foo(char x)
{
...
Foo(x, 0); // this line does NOT help initialize the this object!!
...
}
You can sometimes combine two constructors via a default parameter:


class Foo {
public:
Foo(char x, int y=0); // this line combines the two constructors
...
};
If that doesn't work, e.g., if there isn't an appropriate default parameter that combines the two
constructors, sometimes you can share their common code in a private init() member function:


class Foo {
public:
Foo(char x);
Foo(char x, int y);
...
private:
void init(char x, int y);
};

Foo::Foo(char x)
{
init(x, int(x) + 7);
...
}

Foo::Foo(char x, int y)
{
init(x, y);
...
}

void Foo::init(char x, int y)
{
...
}
BTW do NOT try to achieve this via placement new. Some people think they can say new(this) Foo(x, int(x)+7) within the body of Foo::Foo(char). However that is bad, bad, bad. Please don't write me and tell me that it seems to work on your particular version of your particular compiler; it's bad. Constructors do a bunch of little magical things behind the scenes, but that bad technique steps on those partially constructed bits. Just say no.

Q: Is the default constructor for Fred always Fred::Fred()?
A: No. A "default constructor" is a constructor that can be called with no arguments. One example of this is a constructor that takes no parameters:

class Fred {
public:
Fred(); // Default constructor: can be called with no args
...
};
Another example of a "default constructor" is one that can take arguments, provided they are
given default values:

class Fred {
public:
Fred(int i=3, int j=5); // Default constructor: can be called with no args
...
};

Q: Which constructor gets called when I create an array of Fred objects?
A: Fred's default constructor (except as discussed below).

class Fred {
public:
Fred();
...
};

int main()
{
Fred a[10]; calls the default constructor 10 times
Fred* p = new Fred[10]; calls the default constructor 10 times
...
}
If your class doesn't have a default constructor, you'll get a compile-time error when you attempt
to create an array using the above simple syntax:

class Fred {
public:
Fred(int i, int j); assume there is no default constructor
...
};

int main()
{
Fred a[10]; ERROR: Fred doesn't have a default constructor
Fred* p = new Fred[10]; ERROR: Fred doesn't have a default constructor
...
}
However, even if your class already has a default constructor, you should try to use std::vector
rather than an array (arrays are evil). std::vector lets you decide to use any constructor, not just
the default constructor:

#include

int main()
{
std::vector a(10, Fred(5,7)); the 10 Fred objects in std::vector a will be initialized with Fred(5,7)
...
}
Even though you ought to use a std::vector rather than an array, there are times when an array
might be the right thing to do, and for those, you might need the "explicit initialization of arrays"
syntax. Here's how:

class Fred {
public:
Fred(int i, int j); assume there is no default constructor
...
};

int main()
{
Fred a[10] = {
Fred(5,7), Fred(5,7), Fred(5,7), Fred(5,7), Fred(5,7), // The 10 Fred objects are
Fred(5,7), Fred(5,7), Fred(5,7), Fred(5,7), Fred(5,7) // initialized using Fred(5,7)
};
...
}
Of course you don't have to do Fred(5,7) for every entry you can put in any numbers you want, even parameters or other variables.

Finally, you can use placement-new to manually initialize the elements of the array. Warning: it's ugly: the raw array can't be of type Fred, so you'll need a bunch of pointer-casts to do things like compute array index operations. Warning: it's compiler- and hardware-dependent: you'll need to make sure the storage is aligned with an alignment that is at least as strict as is required for objects of class Fred. Warning: it's tedious to make it exception-safe: you'll need to manually
destruct the elements, including in the case when an exception is thrown part-way through the loop that calls the constructors. But if you really want to do it anyway, read up on placement- new. (BTW placement-new is the magic that is used inside of std::vector. The complexity of getting everything right is yet another reason to use std::vector.)

By the way, did I ever mention that arrays are evil? Or did I mention that you ought to use a std::vector unless there is a compelling reason to use an array?

Q: Should my constructors use "initialization lists" or "assignment"?
A: Initialization lists. In fact, constructors should initialize as a rule all member objects in the initialization list. One exception is discussed further down.

Consider the following constructor that initializes member object x_ using an initialization list:
Fred::Fred() : x_(whatever) { }. The most common benefit of doing this is improved
performance. For example, if the expression whatever is the same type as member variable x_, the result of the whatever expression is constructed directly inside x_ the compiler does not make a separate copy of the object. Even if the types are not the same, the compiler is usually able to do a better job with initialization lists than with assignments.

The other (inefficient) way to build constructors is via assignment, such as: Fred::Fred() { x_ = whatever; }. In this case the expression whatever causes a separate, temporary object to be created, and this temporary object is passed into the x_ object's assignment operator. Then that temporary object is destructed at the ;. That's inefficient.

As if that wasn't bad enough, there's another source of inefficiency when using assignment in a constructor: the member object will get fully constructed by its default constructor, and this might, for example, allocate some default amount of memory or open some default file. All this work could be for naught if the whatever expression and/or assignment operator causes the object to close that file and/or release that memory (e.g., if the default constructor didn't allocate a large enough pool of memory or if it opened the wrong file).

Conclusion: All other things being equal, your code will run faster if you use initialization lists rather than assignment.

Note: There is no performance difference if the type of x_ is some built-in/intrinsic type, such as int or char* or float. But even in these cases, my personal preference is to set those data members in the initialization list rather than via assignment for consistency. Another symmetry argument in favor of using initialization lists even for built-in/intrinsic types: non-static const and non-
static reference data members can't be assigned a value in the constructor, so for symmetry it makes sense to initialize everything in the initialization list.

Now for the exceptions. Every rule has exceptions (hmmm; does "every rule has exceptions"
have exceptions? reminds me of Gdel's Incompleteness Theorems), and there are a couple of exceptions to the "use initialization lists" rule. Bottom line is to use common sense: if it's cheaper, better, faster, etc. to not use them, then by all means, don't use them. This might happen when your class has two constructors that need to initialize the this object's data members in
different orders. Or it might happen when two data members are self-referential. Or when a data- member needs a reference to the this object, and you want to avoid a compiler warning about using the this keyword prior to the { that begins the constructor's body (when your particular compiler happens to issue that particular warning). Or when you need to do an if/throw test on a variable (parameter, global, etc.) prior to using that variable to initialize one of your this members. This list is not exhaustive; please don't write me asking me to add another "Or
when...". The point is simply this: use common sense.

Q: Should you use the this pointer in the constructor?
A: Some people feel you should not use the this pointer in a constructor because the object is not fully formed yet. However you can use this in the constructor (in the {body} and even in the initialization list) if you are careful.

Here is something that always works: the {body} of a constructor (or a function called from the constructor) can reliably access the data members declared in a base class and/or the data members declared in the constructor's own class. This is because all those data members are guaranteed to have been fully constructed by the time the constructor's {body} starts executing.

Here is something that never works: the {body} of a constructor (or a function called from the constructor) cannot get down to a derived class by calling a virtual member function that is overridden in the derived class. If your goal was to get to the overridden function in the derived class, you won't get what you want. Note that you won't get to the override in the derived class independent of how you call the virtual member function: explicitly using the this pointer (e.g.,
this->method()), implicitly using the this pointer (e.g., method()), or even calling some other function that calls the virtual member function on your this object. The bottom line is this: even if the caller is constructing an object of a derived class, during the constructor of the base class, your object is not yet of that derived class. You have been warned.

Here is something that sometimes works: if you pass any of the data members in this object to another data member's initializer, you must make sure that the other data member has already been initialized. The good news is that you can determine whether the other data member has (or has not) been initialized using some straightforward language rules that are independent of the particular compiler you're using. The bad news it that you have to know those language rules (e.g., base class sub-objects are initialized first (look up the order if you have multiple and/or virtual inheritance!), then data members defined in the class are initialized in the order in which they appear in the class declaration). If you don't know these rules, then don't pass any data member from the this object (regardless of whether or not you explicitly use the this keyword) to any other data member's initializer! And if you do know the rules, please be careful.

Q: What is the "Named Constructor Idiom"?
A: A technique that provides more intuitive and/or safer construction operations for users of your class.

The problem is that constructors always have the same name as the class. Therefore the only way to differentiate between the various constructors of a class is by the parameter list. But if there are lots of constructors, the differences between them become somewhat subtle and error prone.

With the Named Constructor Idiom, you declare all the class's constructors in the private or protected sections, and you provide public static methods that return an object. These static methods are the so-called "Named Constructors." In general there is one such static method for each different way to construct an object.

For example, suppose we are building a Point class that represents a position on the X-Y plane.
Turns out there are two common ways to specify a 2-space coordinate: rectangular coordinates
(X+Y), polar coordinates (Radius+Angle). (Don't worry if you can't remember these; the point
isn't the particulars of coordinate systems; the point is that there are several ways to create a
Point object.) Unfortunately the parameters for these two coordinate systems are the same: two
floats. This would create an ambiguity error in the overloaded constructors:


class Point {
public:
Point(float x, float y); // Rectangular coordinates
Point(float r, float a); // Polar coordinates (radius and angle)
// ERROR: Overload is Ambiguous: Point::Point(float,float)
};

int main()
{
Point p = Point(5.7, 1.2); // Ambiguous: Which coordinate system?
...
}
One way to solve this ambiguity is to use the Named Constructor Idiom:


#include // To get sin() and cos()

class Point {
public:
static Point rectangular(float x, float y); // Rectangular coord's
static Point polar(float radius, float angle); // Polar coordinates
// These static methods are the so-called "named constructors"
...
private:
Point(float x, float y); // Rectangular coordinates
float x_, y_;
};

inline Point::Point(float x, float y)
: x_(x), y_(y) { }

inline Point Point::rectangular(float x, float y)

{ return Point(x, y); }

inline Point Point::polar(float radius, float angle)
{ return Point(radius*cos(angle), radius*sin(angle)); }
Now the users of Point have a clear and unambiguous syntax for creating Points in either
coordinate system:


int main()
{
Point p1 = Point::rectangular(5.7, 1.2); // Obviously rectangular
Point p2 = Point::polar(5.7, 1.2); // Obviously polar
...
}
Make sure your constructors are in the protected section if you expect Point to have derived classes.

The Named Constructor Idiom can also be used to make sure your objects are always created via new.

Note that the Named Constructor Idiom, at least as implemented above, is just as fast as directly calling a constructor modern compilers will not make any extra copies of your object.

C++ Interview Questions and Answers (1)

C++ Interview Questions and Answers (1)

Q: Is it possible to have Virtual Constructor? If yes, how? If not, Why not possible?
A: There is nothing like Virtual Constructor. The Constructor can’t be virtual as the constructor
is a code which is responsible for creating an instance of a class and it can’t be delegated to
any other object by virtual keyword means.

Q: What is constructor or ctor?
A: Constructor creates an object and initializes it. It also creates vtable for virtual functions. It is
different from other methods in a class.

Q: What about Virtual Destructor?
A: Yes there is a Virtual Destructor. A destructor can be virtual as it is possible as at runtime
depending on the type of object caller is calling to, proper destructor will be called.

Q: What is the difference between a copy constructor and an overloaded assignment operator?
A: A copy constructor constructs a new object by using the content of the argument object. An
overloaded assignment operator assigns the contents of an existing object to another existing
object of the same class.

Q: Can a constructor throws an exception? How to handle the error when the constructor fails?
A:The constructor never throws an error.

Q: What is default constructor?
A: Constructor with no arguments or all the arguments has default values.

Q: What is copy constructor?
A: Constructor which initializes the it's object member variables ( by
shallow copying) with another object of the same class. If you don't implement one in your class
then compiler implements one for you. for example:
(a) Boo Obj1(10); // calling Boo constructor
(b) Boo Obj2(Obj1); // calling boo copy constructor
(c) Boo Obj2 = Obj1;// calling boo copy constructor

Q: When are copy constructors called?
A: Copy constructors are called in following cases:
(a) when a function returns an object of that
class by value
(b) when the object of that class is passed by
value as an argument to a function
(c) when you construct an object based on another
object of the same class
(d) When compiler generates a temporary object


Q: Can a copy constructor accept an object of the same class as parameter, instead of reference
of the object?
A: No. It is specified in the definition of the copy constructor itself. It should generate an error if
a programmer specifies a copy constructor with a first argument that is an object and not a
reference.

Q: What is conversion constructor?
A: constructor with a single argument makes that constructor as conversion ctor and it can be
used for type conversion.
for example:
class Boo
{
public:
Boo( int i );
};
Boo BooObject = 10 ; // assigning int 10 Boo object

Q:What is conversion operator??
A:class can have a public method for specific data type conversions.
for example:
class Boo
{
double value;
public:
Boo(int i )
operator double()
{
return value;
}
};
Boo BooObject;
double i = BooObject; // assigning object to variable i of type double.
now conversion operator gets called to assign the value.

Q: How can I handle a constructor that fails?
A: throw an exception. Constructors don't have a return type, so it's not possible to use return codes. The best way to signal constructor failure is therefore to throw an exception.

Q: How can I handle a destructor that fails?
A: Write a message to a log-_le. But do not throw an exception. The C++ rule is that you must never throw an exception from a destructor that is being called during the "stack unwinding" process of another exception. For example, if someone says throw Foo(), the stack will be unwound so all the stack frames between the throw Foo() and the } catch (Foo e) { will get popped. This is called stack unwinding. During stack unwinding, all the local objects in all



those stack frames are destructed. If one of those destructors throws an exception (say it throws a Bar object), the C++ runtime system is in a no-win situation: should it ignore the Bar and end up in the } catch (Foo e) { where it was originally headed? Should it ignore the Foo and look for a } catch (Bare) { handler? There is no good answer:either choice loses information. So the C++ language guarantees that it will call terminate() at this point, and terminate() kills the process. Bang you're dead.

Q: What is Virtual Destructor?
A: Using virtual destructors, you can destroy objects without knowing their type - the correct destructor for the object is invoked using the virtual function mechanism. Note that destructors can also be declared as pure virtual functions for abstract classes. if someone will derive from your class, and if someone will say "new Derived", where "Derived" is derived from your class, and if someone will say delete p, where the actual object's type is "Derived" but the pointer p's type is your class.

Q: Can a copy constructor accept an object of the same class as parameter, instead of reference of the object?
A: No. It is specified in the definition of the copy constructor itself. It should generate an error if a programmer specifies a copy constructor with a first argument that is an object and not a reference.

Q: What's the order that local objects are destructed?
A: In reverse order of construction: First constructed, last destructed.

In the following example, b's destructor will be executed first, then a's destructor:

void userCode()
{
Fred a;
Fred b;
...
}

Q: What's the order that objects in an array are destructed?
A: In reverse order of construction: First constructed, last destructed.

In the following example, the order for destructors will be a[9], a[8], ..., a[1], a[0]:

void userCode()
{
Fred a[10];
...
}

Q: Can I overload the destructor for my class?

A: No.

You can have only one destructor for a class Fred. It's always called Fred::~Fred(). It never takes any parameters, and it never returns anything.

You can't pass parameters to the destructor anyway, since you never explicitly call a destructor (well, almost never).

Q: Should I explicitly call a destructor on a local variable?
A: No!

The destructor will get called again at the close } of the block in which the local was created.
This is a guarantee of the language; it happens automagically; there's no way to stop it from happening. But you can get really bad results from calling a destructor on the same object a second time! Bang! You're dead!

Q: What if I want a local to "die" before the close } of the scope in which it was created? Can I call a destructor on a local if I really want to?
A: No! [For context, please read the previous FAQ].

Suppose the (desirable) side effect of destructing a local File object is to close the File. Now suppose you have an object f of a class File and you want File f to be closed before the end of the scope (i.e., the }) of the scope of object f:

void someCode()
{
File f;

...insert code that should execute when f is still open...

We want the side-effect of f's destructor here!

...insert code that should execute after f is closed...
}
There is a simple solution to this problem. But in the mean time, remember: Do not explicitly call the destructor!

Q: OK, OK already; I won't explicitly call the destructor of a local; but how do I handle the above situation?
A: Simply wrap the extent of the lifetime of the local in an artificial block {...}:

void someCode()
{
{

File f;
...insert code that should execute when f is still open...
} f's destructor will automagically be called here!

...insert code here that should execute after f is closed...}

Q: What if I can't wrap the local in an artificial block?
A: Most of the time, you can limit the lifetime of a local by wrapping the local in an artificial block ({...}). But if for some reason you can't do that, add a member function that has a similar effect as the destructor. But do not call the destructor itself!

For example, in the case of class File, you might add a close() method. Typically the destructor will simply call this close() method. Note that the close() method will need to mark the File object so a subsequent call won't re-close an already-closed File. E.g., it might set the file Handle_ data member to some nonsensical value such as -1, and it might check at the beginning to see if the file Handle_ is already equal to -1:

class File {
public:
void close();
~File();
...
private:
int fileHandle_; // fileHandle_ >= 0 if/only-if it's open
};

File::~File()
{
close();
}

void File::close()
{
if (fileHandle_ >= 0) {
...insert code to call the OS to close the file...
fileHandle_ = -1;
}
}
Note that the other File methods may also need to check if the fileHandle_ is -1 (i.e., check if the
File is closed).

Note also that any constructors that don't actually open a file should set fileHandle_ to -1.

Q: But can I explicitly call a destructor if I've allocated my object with new?
A: Probably not.


Unless you used placement new, you should simply delete the object rather than explicitly calling the destructor. For example, suppose you allocated the object via a typical new expression:


Fred* p = new Fred();
Then the destructor Fred::~Fred() will automagically get called when you delete it via:


delete p; // Automagically calls p->~Fred()
You should not explicitly call the destructor, since doing so won't release the memory that was allocated for the Fred object itself. Remember: delete p does two things: it calls the destructor and it deallocates the memory.

Q: What is "placement new" and why would I use it?
A: There are many uses of placement new. The simplest use is to place an object at a particular location in memory. This is done by supplying the place as a pointer parameter to the new part of a new expression:

#include // Must #include this to use "placement new"
#include "Fred.h" // Declaration of class Fred

void someCode()
{
char memory[sizeof(Fred)]; // Line #1
void* place = memory; // Line #2

Fred* f = new(place) Fred(); // Line #3 (see "DANGER" below)
// The pointers f and place will be equal

...
}
Line #1 creates an array of sizeof(Fred) bytes of memory, which is big enough to hold a Fred object.
Line #2 creates a pointer place that points to the first byte of this memory (experienced C programmers will note that this step was unnecessary; it's there only to make the code more obvious).
Line #3 essentially just calls the constructor Fred::Fred(). The this pointer in the Fred constructor will be equal to place. The returned pointer f will therefore be equal to place.

ADVICE: Don't use this "placement new" syntax unless you have to. Use it only when you really
care that an object is placed at a particular location in memory. For example, when your
hardware has a memory-mapped I/O timer device, and you want to place a Clock object at that
memory location.

DANGER: You are taking sole responsibility that the pointer you pass to the "placement new" operator points to a region of memory that is big enough and is properly aligned for the object type that you're creating. Neither the compiler nor the run-time system make any attempt to check whether you did this right. If your Fred class needs to be aligned on a 4 byte boundary but you supplied a location that isn't properly aligned, you can have a serious disaster on your hands
(if you don't know what "alignment" means, please don't use the placement new syntax). You have been warned.

You are also solely responsible for destructing the placed object. This is done by explicitly calling the destructor:

void someCode()
{
char memory[sizeof(Fred)];
void* p = memory;
Fred* f = new(p) Fred();
...
f->~Fred(); // Explicitly call the destructor for the placed object
}
This is about the only time you ever explicitly call a destructor.

Note: there is a much cleaner but more sophisticated way of handling the destruction / deletion
situation.
Q: When I write a destructor, do I need to explicitly call the destructors for my member objects?
A: No. You never need to explicitly call a destructor (except with placement new).

A class's destructor (whether or not you explicitly define one) automagically invokes the
destructors for member objects. They are destroyed in the reverse order they appear within the
declaration for the class.

class Member {
public:
~Member();
...
};

class Fred {
public:
~Fred();
...
private:
Member x_;
Member y_;
Member z_;

};

Fred::~Fred()
{
// Compiler automagically calls z_.~Member()
// Compiler automagically calls y_.~Member()
// Compiler automagically calls x_.~Member()
}

VMware Cloud Learning Video's

Here is a nice summary list of all VMworld US 2018 Breakout session with the respective video playback & download URLs. Enjoy! Bra...