473,763 Members | 1,908 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

some C++-specific interview questions

I'm not the world's greatest C++ programmer, so I had a hard
time with these. Some help would be appreciated.

1. Comment on the declaration of function Bar() below:
class Foo
{
static int Bar(int i) const;
}

(I said that since Bar is a static method, it can only access
static variables, not member variables, so the const is
irrelevant.)
2. If you have virtual functions in your class, do you need a virtual
destructor? Why?

(My gut answer was that no, you don't NEED a virtual destructor
unless the derived class is handling its own dynamically-managed
data.)

3. Comment on the following function. What would you change? State
your assumptions:

string & Foo()
{
string default_string = "default answer";
for (vector<node>:: iterator iter = mynodes.begin() ;
iter != mynodes.end();
iter++)
{
cout << iter;
}
return default_string;
}
4. When would you use private inheritence? (I have never personally
used this.)

5. Where in memory is the virtual function lookup table stored?
(I found this one to be way too detailed for me.)

6. Consider member initialisation lists. Why are they needed? Why are
they considered more efficient than initialising members in the body of
the constructor?

Sep 7 '06 #1
39 2529
Digital Puer wrote:
I'm not the world's greatest C++ programmer, so I had a hard
time with these. Some help would be appreciated.
The next problem is your interviewer might not be the world's greatest,
either... ;-)
1. Comment on the declaration of function Bar() below:
class Foo
{
static int Bar(int i) const;
}

(I said that since Bar is a static method, it can only access
static variables, not member variables, so the const is
irrelevant.)
I suspect it should not even compile.
2. If you have virtual functions in your class, do you need a virtual
destructor? Why?
(My gut answer was that no, you don't NEED a virtual destructor
unless the derived class is handling its own dynamically-managed
data.)
In this case, you must answer twice; both the safest way and the technically
correct way. The safest way is "all destructors are virtual unless profiling
reveals the need to remove a virtual". That's safe, because a teammate might
write a class that inherits your class, and then write a 'delete' that uses
a pointer to your class, not the derived class. Deleting such an object,
without a virtual destructor, is undefined behavior.

The technical answer is no, you never are required to make a destructor
virtual, if you know that nobody will ever delete it through a pointer to
the base class.

And the other virtual methods are only indirectly indicated. They don't
influence the technical or semantic decision to make the destructor virtual.
Indirectly, semantically, you should not inherit from a class with no
virtual methods, hence you should never delete a pointer to its base class.

At least the question wasn't "If a destructor releases no resources, must it
be virtual?" That implies the common fallacy that deleting a pointer to the
base class will only create undefined behavior if it creates a leak. The
undefined behavior actually starts at destructor time, regardless what then
leaks.
3. Comment on the following function. What would you change? State
your assumptions:

string & Foo()
{
string default_string = "default answer";
for (vector<node>:: iterator iter = mynodes.begin() ;
iter != mynodes.end();
iter++)
{
cout << iter;
}
return default_string;
}
It returns a reference to a destructed local, so that's undefined.

Next, vector<nodeis not typedeffed.

Next, the default_string has nothing to do with the for-loop, which could be
just a decoy. Regardless, you should announce the function does two
independent things and should be split in two.

Next, cout << iter is poorly defined to produce something useless, possibly
a pointer address. If operator<< is defined for 'node', then cout << * iter
might be more useful.

Next, all iterators should always be called 'it'. ;-)
4. When would you use private inheritence? (I have never personally
used this.)
Per /C++ Coding Standards/ by Sutter and Alex A., you should prefer it to
public inheritance.

Consider the Abstract Template Pattern, but where only the derived classes
know they call a secret parent that then, in turn, calls their specialized
methods to help it perform their templated action.

(Warning: That's not a C++ template...)
5. Where in memory is the virtual function lookup table stored?
(I found this one to be way too detailed for me.)
I don't know how Standard this answer is, but it's stored in the initialized
global data segment. This fact (even its accurate version) should never be
used in practice, except in the sickest debugging situations.
6. Consider member initialisation lists. Why are they needed?
Because they explicitly declare intent, to both your colleagues and to the
compiler.
Why are
they considered more efficient than initialising members in the body of
the constructor?
Because the compiler can generate the most efficient code to implement them.
They are defined to occur in the same order as the members appear in the
class's definition, so the compiler could get as efficient as an unrolled
loop to stomp them all in.

Further, some systems can provide a warning if you write them out of order.
This helps your code self-correct.

Next, your constructor's body should be exception neutral and safe. So
putting pointer(NULL) in the member list, and then a pointer=new in the
body, can lead to a safer 'delete' if the constructor then blows. (But the
destructor won't call, so still prefer smart pointers!)

Next, if any member's initialization throws an exception, the stack unwinder
will call the destructor of each fully constructed member, in reverse order.

In general, efficiency is a poor taskmaster. Premature optimization is the
root of all evil. In this case, you may err on the side of efficiency if the
result is also _cognitively_ efficient. Member initialization lists are
easier to comprehend, after you train to recognize them as important parts
of constructors. So follow this rule: Never enter the opening { of a
constructor with any member in an uninitialized state.

You can get that rule easily by only using smart data members, such as smart
pointers and other contained objects with default constructors.

--
Phlip
http://c2.com/cgi/wiki?ZeekLand <-- NOT a blog!!!
Sep 7 '06 #2

Digital Puer wrote:
1. Comment on the declaration of function Bar() below:
class Foo
{
static int Bar(int i) const;
}

(I said that since Bar is a static method, it can only access
static variables, not member variables, so the const is
irrelevant.)
I think you are right. const is irrelavant.
2. If you have virtual functions in your class, do you need a virtual
destructor? Why?

(My gut answer was that no, you don't NEED a virtual destructor
unless the derived class is handling its own dynamically-managed
data.)
What about the private data members of base class? They are not
inherited in any case. So how to delete them? I think we need that in
both classes.

I can't understand the third one.
4. When would you use private inheritence? (I have never personally
used this.)
me too. but it is used to make all public and protected members of base
class as private members in derived class. (I think you already know
this)
5. Where in memory is the virtual function lookup table stored?
(I found this one to be way too detailed for me.)
The V-table pointer is generally stored just after the elements of the
base class. That means it is heap. When you see the class size, the
class size will contain member variables size and (no of virtual
functions * pointer size)
6. Consider member initialisation lists. Why are they needed? Why are
they considered more efficient than initialising members in the body of
the constructor?
I am just guessing on the 6th Question.
Why are they needed?
They are generally used to initialize const member variables (also non
const).
why are they more efficient?
really don't know. but normally when you write in the body, you write
statement wise. but here you write using comma operator and assign
through braces. So does this bring any performance? please let me know.

-- Murali Krishna

Sep 7 '06 #3
Digital Puer wrote:
I'm not the world's greatest C++ programmer, so I had a hard
time with these. Some help would be appreciated.

1. Comment on the declaration of function Bar() below:
class Foo
{
static int Bar(int i) const;
}

(I said that since Bar is a static method, it can only access
static variables, not member variables, so the const is
irrelevant.)
I think it doesn't compile because const is not permitted with static
functions
>
2. If you have virtual functions in your class, do you need a virtual
destructor? Why?

(My gut answer was that no, you don't NEED a virtual destructor
unless the derived class is handling its own dynamically-managed
data.)
Virtual destructor is needed for calling the apropiate destructor when
delete a pointer-to-base. Heap memory is one reason, but in general, is
necessary when derived class's destructor has something to do.

In general, when yo have virtual functions make destructor virtual.

3. Comment on the following function. What would you change? State
your assumptions:

string & Foo()
{
string default_string = "default answer";
for (vector<node>:: iterator iter = mynodes.begin() ;
iter != mynodes.end();
iter++)
{
cout << iter;
}
return default_string;
}
You are returning a reference to local data of your function. As it's
local it will be destroyed when function is finished.
Usually when you construct a constact value inside a function you make
the variable static. With static variable you can return value by
reference, but I'd make return type const, for fobidding modification on
its value.

Iterator acts like a pointer, thus you must derrefence it:
cout << *iter;

4. When would you use private inheritence? (I have never personally
used this.)
When inheritance is for reusing implementation but hasn't a is-a
relationship. With private inheritance implicit pointer-to-base
conversion is not permitted.
>
5. Where in memory is the virtual function lookup table stored?
(I found this one to be way too detailed for me.)
I think vtable details are not covered in C++ standard (I'm not sure,
but I think it).
Usually compilers construct it (I don't know where), and pointers and
references have a "link" to it.
I'm not sure on this question, because I don't remember well what I read
about it in the past. I suggest you to read Stanley B. Lippman's "Inside
the C++ object model".
6. Consider member initialisation lists. Why are they needed? Why are
they considered more efficient than initialising members in the body of
the constructor?
They are needed for initializating not-default constructor of base clases.
When you don't initialise a member in an initialisation list, it is
initialised by default, thus when you initialise it inside the body of a
constructor it's initialised twice.
When you initialise a member in the initialisation list, that is the
unique inisialization.

Sep 7 '06 #4
> string & Foo()
{
string default_string = "default answer";
for (vector<node>:: iterator iter = mynodes.begin() ;
iter != mynodes.end();
iter++)
{
cout << iter;
}
return default_string;
}

It returns a reference to a destructed local, so that's undefined.

Next, vector<nodeis not typedeffed.

Next, the default_string has nothing to do with the for-loop, which
could be just a decoy. Regardless, you should announce the function
does two independent things and should be split in two.

Next, cout << iter is poorly defined to produce something useless,
possibly a pointer address. If operator<< is defined for 'node',
then cout << * iter might be more useful.

Next, all iterators should always be called 'it'. ;-)
I'd make that:
static string default_string = "default answer";

and change iter++ to ++iter, since that's a micro optimization.

>5. Where in memory is the virtual function lookup table stored?
(I found this one to be way too detailed for me.)

I don't know how Standard this answer is, but it's stored in the
initialized global data segment. This fact (even its accurate
version) should never be used in practice, except in the sickest
debugging situations.
I think that depends on the compiler. The std does not say anything
about it.
Sep 7 '06 #5
Murali Krishna wrote:
Digital Puer wrote:
>>6. Consider member initialisation lists. Why are they needed? Why are
they considered more efficient than initialising members in the body of
the constructor?

why are they more efficient?
really don't know. but normally when you write in the body, you write
statement wise. but here you write using comma operator and assign
through braces. So does this bring any performance? please let me know.
The comma operator isn't involved in member initialization lists, that's
just part of C++ syntax (like the semi-colon at the end of each
statement). Member initializations is generally to be prefered, since
members that are initialized in the member initialization list are
initialized by their constructors. If a member is not mentioned in the
member initialization list, it's default constructor will be invoked
(which would assign values that will most likely get overwritten in the
constructor anyway).
Consider the following program and its output:

#include <iostream>
class A
{
int m_a;
public:
A ()
: m_a (0)
{ std::cout << "default constructor of A invoked.";
std::cout << std::endl;}
A (int p_a)
: m_a (p_a)
{ std::cout << "initializa tion constructor of A invoked.";
std::cout << std::endl;}
A& operator= (int p_a)
{ m_a = p_a;
std::cout << "Assignment operator for A invoked.";
std::cout << std::endl;
return *this;}
};

class B
{
A m_Aobj;
public:
B (int p_b)
: m_Aobj (p_b)
{}
};

class C
{
A m_Aobj;
public:
C (int p_b)
{ m_Aobj = p_b; }
};

int main ()
{
B b (0);
C c (0);
return 0;
}

In those cases where you have no default constructor available, you
cannot get around member initialization lists.
Sep 7 '06 #6
2. If you have virtual functions in your class, do you need a virtual
destructor? Why?

(My gut answer was that no, you don't NEED a virtual destructor
unless the derived class is handling its own dynamically-managed
data.)

What about the private data members of base class? They are not
inherited in any case. So how to delete them? I think we need that in
both classes.
Of course private members are inherited.
The base class methods access them.

5. Where in memory is the virtual function lookup table stored?
(I found this one to be way too detailed for me.)

The V-table pointer is generally stored just after the elements of the
base class. That means it is heap. When you see the class size, the
class size will contain member variables size and (no of virtual
functions * pointer size)
As stated elsewhere, there is no place where the vtable has to be
stored.
But what you describe would be a very poor implementation.

In most cases, with each instance, there is ONE pointer to a vtable of
that class.
The vtable then contains one pointer per virtual member function and
exists
only once per class.
In g++ this is in the object file (.o) where the destructor of that
class is defined.

It is nice that you want to help, but please comment only on stuff you
really know.
Otherwise your answer just causes confusion.

Regards,
Marc

Sep 7 '06 #7
"Carlos Martinez" <cm****@nospam. tid.eswrote in message
news:ed******** *@news.hi.inet. ..
4. When would you use private inheritence? (I have never personally
used this.)

When inheritance is for reusing implementation but hasn't a is-a
relationship. With private inheritance implicit pointer-to-base
conversion is not permitted.
But you could just use simple composition anyway - include class B as a data
member of class D instead of as a private parent. I've never found a need
for private inheritance, though the FAQ has a couple of interesting bits on
it.
6. Consider member initialisation lists. Why are they needed? Why are
they considered more efficient than initialising members in the body of
the constructor?

They are needed for initializating not-default constructor of base clases.
When you don't initialise a member in an initialisation list, it is
initialised by default, thus when you initialise it inside the body of a
constructor it's initialised twice.
Minor nit: It's only initialized once, and then assigned to.

Philip

Sep 7 '06 #8

"Phlip" <ph******@yahoo .comwrote in message
news:Mv******** **********@news svr29.news.prod igy.net...
At least the question wasn't "If a destructor releases no resources, must
it
be virtual?" That implies the common fallacy that deleting a pointer to
the
base class will only create undefined behavior if it creates a leak. The
undefined behavior actually starts at destructor time, regardless what
then
leaks.
Thanks, I didn't know that. Learn something new every day.

Philip

Sep 7 '06 #9
Philip Potter wrote:
"Carlos Martinez" <cm****@nospam. tid.eswrote in message
news:ed******** *@news.hi.inet. ..
>>4. When would you use private inheritence? (I have never personally
used this.)
When inheritance is for reusing implementation but hasn't a is-a
relationship . With private inheritance implicit pointer-to-base
conversion is not permitted.

But you could just use simple composition anyway - include class B as a data
member of class D instead of as a private parent. I've never found a need
for private inheritance, though the FAQ has a couple of interesting bits on
it.
Yes, the same thing may be implemented in different ways. What you say
is called dellegation and is an alternate to inheritance. It's used for
example to reduce multiple inheritance to single inheritance (inherit
from main concept and delegate the others.

Private inheritance is not the only way of reusing implementation, but
it's a way.
I prefer private inheritance over delegation for example when I must
partially export base's interface, with base::myMethod

>>6. Consider member initialisation lists. Why are they needed? Why are
they considered more efficient than initialising members in the body of
the constructor?
They are needed for initializating not-default constructor of base clases.
When you don't initialise a member in an initialisation list, it is
initialised by default, thus when you initialise it inside the body of a
constructor it's initialised twice.

Minor nit: It's only initialized once, and then assigned to.
Yes. I prefer for simplicity, to create an init member function called
from constructor instead of initialization list, because you centralize
the "reset" of attributes in one function instead of duplicating
initialisation of members in initialisation list of different
constructors and "reset" functions (adding an attribute generates fewer
changes on code because it is located only in a portion of code
(initialisation function)).
But academically, it's a question of performance to prefer
initialisation list over assignment in the body of constructor.
>
Philip
Sep 7 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
3103
by: Jeff Wagner | last post by:
I am in the process of learning Python (obsessively so). I've been through a few tutorials and read a Python book that was lent to me. I am now trying to put what I've learned to use by rewriting that Numerology program I wrote years ago in VB. There are times I am totally stuck (for instance, I just had an idea to put the numerical values of the alphabet and months of the year in a dictionary located in a function. Then, I can import the...
1
2608
by: Az Tech | last post by:
Hi people, (Sorry for the somewhat long post). I request some of the people on this group who have good experience using object-orientation in the field, to please give some good ideas for topics to include in a course on object-orientation that I'm going to conduct. (I will later summarize all the replies and discussion, for the
2
1333
by: John Viele | last post by:
Every time I create ASP.NET pages that do any significant data access, I find myself having to deal with the same problems: managing data object creation, the SQL connection object especially. Problem 1: If I have a pile of data adapters on a page, I typically only need a single SQL connection object, though the designer always tries to add a new one for each data adapter. So I have to manually weed out the extras and set the data...
3
1591
by: Mike | last post by:
Hey guys I am pulling my hair out on this problem!!!!! Any help or ideas or comments on how to make this work I would be grateful! I have been working on this for the past 4 days and nothing I do seems to get me any closer to the solution. Below is a program that I am working on for a class project. The original code was provided for us which is what I have below. What we have to do is make the app run so that it allows the user to add...
193
9634
by: Michael B. | last post by:
I was just thinking about this, specifically wondering if there's any features that the C specification currently lacks, and which may be included in some future standardization. Of course, I speak only of features in the spirit of C; something like object-orientation, though a nice feature, does not belong in C. Something like being able to #define a #define would be very handy, though, e.g: #define DECLARE_FOO(bar) #define...
1
1489
by: srikanth | last post by:
hi, I have one file it filled with some values in rows/colums. some times, some variables (in a particular row& column) may not be filled. depending on the kind its filled i will go for defferent kind of operations in my C-programm. with fgets and sscanf, i can get values in one line, but some times some particular row&column may be not filled. then how can my programm knows its not filled. means it cant take empty space as NaN(not a...
48
2174
by: yezi | last post by:
Hi, all: I want to record some memory pointer returned from malloc, is possible the code like below? int memo_index; int i,j; char *tmp; for (i=0;i<10;i++){
3
28888
by: David | last post by:
Hello. I have XML file like this: ========================================== <?xml version="1.0" encoding="utf-8" ?> <Language> <English> <Captions> <Name>Some caption</Name> </Captions>
6
2346
by: TPJ | last post by:
Help me please, because I really don't get it. I think it's some stupid mistake I make, but I just can't find it. I have been thinking about it for three days so far and I still haven't found any solution. My code can be downloaded from here: http://www.tprimke.net/konto/PyObject-problem.tar.bz2. There are some scripts for GNU/Linux system (bash to be precise). All you need to know is that there are four classes. (Of course, you may...
4
1391
by: vunet.us | last post by:
Please, help me with regular expression to grab image source in any text string using the code below. I only need the regex to be plugged in: var strText = "some text <img src='image.jpg'and some text"; var separateBy = ", "; var result = ""; // if no match, use this var allMatches = strText.match(........--->reg exp<---........); if (allMatches) {
0
10149
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9943
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9828
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7370
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6643
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5271
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5410
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3918
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2797
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.