473,770 Members | 1,954 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
39 2531
Phlip wrote:
Digital Puer wrote:
[snip]
>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.
This piece of advice is an over-generalization. Inheritance in C++ is
orthogonal to the use of run-time polymorphism and virtual methods. In
fact, the standard library provides various templates especially designed
to be inherited that do neither provide virtual methods nor virtual
destructors; see: unary_function< or iterator<>.

Your remark is firmly rooted in the OO style of programming, where it makes
perfect sense. However, OO is but one of the various styles of programming
in C++ that make good use of inheritance. Policy based design uses
inheritance often and quite often the policy classes inherited from will
not have virtual methods.

[snip]
Best

Kai-Uwe Bux
Sep 7 '06 #11
Gernot Frisch wrote:
>> 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.
I'd make that:
static string default_string = "default answer";
Return the string by copy. Don't limit how your function can be called.

--
Phlip
http://c2.com/cgi/wiki?ZeekLand <-- NOT a blog!!!
Sep 7 '06 #12
Carlos Martinez wrote:
>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.
Those are both the fallacies I posted about. Make the destructor virtual
only because deleting thru a pointer to a base class is undefined. The
presence of non-trivial destructors, or virtual functions, are secondary
considerations.
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.
It would still refer to a destructed object. Just return by copy.
>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.
That's just restating the question.
>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.
I prescribe /Effective C++/ by Scott Meyers. It has a good explanation why
member initialization lists should initialize every member that needs
initialization. This is still just a style guideline, not a syntactic rule,
but it's important enough to bring up in a job interview!

Let them know you like clean code.

--
Phlip
http://c2.com/cgi/wiki?ZeekLand <-- NOT a blog!!!
Sep 7 '06 #13
Murali Krishna wrote:
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.
That is one of the fallacies I posted about. Make the destructor virtual
only because deleting thru a pointer to a base class is undefined. The
presence of non-trivial destructors, or virtual functions, are secondary
considerations.
>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.
Sometimes it's before, but it's only heap if the entire object is heap.
When you see the class size, the
class size will contain member variables size and (no of virtual
functions * pointer size)
All this is implementation-specific, so if the job doesn't specify a
specific compiler, you must risk announcing the question is non-Standard.

Then answer it almost like you did, and follow with "the vtable can be
global, because it can initialize at startup time, and all objects of a
class may share 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?

I am just guessing on the 6th Question.
Why are they needed?
They are generally used to initialize const member variables (also non
const).
They are required on const and reference member data, and on members and
base classes without default constructors, or with constructors you need to
pass custom arguments to.

Also use them on non-const member data.
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.
Read my first post: "Because they explicitly declare intent, to both your
colleagues and to the
compiler." The more the compiler knows, the better it can optimize. The more
your colleagues know, the faster and safer they can code.

--
Phlip
http://c2.com/cgi/wiki?ZeekLand <-- NOT a blog!!!
Sep 7 '06 #14
Kai-Uwe Bux wrote:
>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.

This piece of advice is an over-generalization. Inheritance in C++ is
orthogonal to the use of run-time polymorphism and virtual methods. In
fact, the standard library provides various templates especially designed
to be inherited that do neither provide virtual methods nor virtual
destructors; see: unary_function< or iterator<>.
That proves my point. You inherit those to use templates, not virtuals, to
override methods.

About the only reason to inherit without overriding is to create a
"convenienc e class". Sometimes, for example, the 'explicit' keyword inside
auto_ptr is annoying, so you inherit auto_ptr<myClas sto create a custom
smart pointer without it.

Actually, that proves my point too. I overrode the constructor on a
template...

Can anyone think of a convenience class that should inherit but doesn't
override something - with virtuals, templates, or some other trick?
Your remark is firmly rooted in the OO style of programming, where it
makes
perfect sense. However, OO is but one of the various styles of programming
in C++ that make good use of inheritance. Policy based design uses
inheritance often and quite often the policy classes inherited from will
not have virtual methods.
I have misplaced my /Effective C++/ book that covers this. Could someone be
a pet and copy in the relevant quote? Scott agrees with us that in rare
cases you inherit without overriding, but in general you don't inherit to
create a "compilable comment", or "so I don't need to delegate to get to the
functions I need."

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

"Phlip" <ph******@yahoo .comwrote in message
news:mU******** *********@newss vr13.news.prodi gy.com...
Carlos Martinez wrote:
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.

It would still refer to a destructed object.
No it wouldn't. It's static.

Philip

Sep 7 '06 #16

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.)
The method cannot be const as you have pointed out. Furthermore I would
go on to say that as it is a private method it is generally best to
remove it from the class declaration altogether and put it in the
anonymous namespace of the file that implements Foo. Then it would
still be accessible only by functions of Foo. I am assuming that Bar
does not access private members of Foo in its implementation. If it
does, it may be better to pass those in as extra parameters, by
reference (const if appropriate).
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.)
Or a protected non-virtual destructor, which would then have the effect
of preventing delete being called on your base class. But since you
have virtual functions so there will be a v-table anyway for the class,
there is no real cost in making the destructor virtual, and anyway you
might want to allow delete to be called on the base class.

Your gut answer was not correct, as others have ponited out.
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;
}
a. Well obviously you can't return a reference to a local variable. You
can make default_string static but only if you change the return type
to const string, Otherwise do the obvious thing and return by value.
You could also return const char * if you are always going to return
the same thing.

b. I'd change the name from Foo() which is meaningless to some name
that describes what the function does.

c. I wouldn't have using namespace std; anywhere above here so I'd
qualify all the members of std.

d. Assuming you don't really want to output the iterator (and why
should it be streamable, it doesn't have to be a pointer) but you want
to output the node, I'd change the code to:

std::copy( mynodes.begin() , mynodes.end(), std::ostream_it erator<node>(
cout ) );

e. This appears to be a class member function. It doesn't modify
anything of the class so make it const.

f. Don't output to cout, give the function an ostream & to output to.

g. And it doesn't look like a template so let's put the implementation
somewhere else. So

std::string MyClass::Output NodesAndReturnS tring( std::ostream & os )
const
{
// implementation here, with cout replaced with os
}

h. Last thing. What is node anyway? vector<nodeis what construct? Are
we reinventing any wheels here?
4. When would you use private inheritence? (I have never personally used this.)
You rarely will, but you would use it when a class is implemented in
terms of another class. The most common occasion is when you might
have:

class Foo : Templ< Foo >

where Templ is a template that is used to implement classes of
different types, but you don't want your users to use it, you only want
them to use Foo.
5. Where in memory is the virtual function lookup table stored?
(I found this one to be way too detailed for me.)
Implementation specific probably, but it's in the "code segment" if
that's what they mean.
6. Consider member initialisation lists. Why are they needed? Why are
they considered more efficient than initialising members in the body of
the constructor?
Should not so much be "why are they needed" rather than "when are they
needed". The are required where you have

a. A base-class or member that has no default constructor, or if the
default constructor is not the one you wish to use to construct it.
b. You have a const member or a reference member (whether const
reference or not).

There is no such thing as initialising members in the body of the
constructor, members are always initialised in the initialiser list.
What you can do, if a member has a default constructor, is use that to
initialise and then modify the member later, usually with assignment.
Constructing with a default constructor then assigning can be less
efficient than constructing with the desired constructor.

If you are referring to pointer members where you need to call new,
beware of exception safety if there is more than one of them and a new
other than the first one fails. Preferably use smart-pointers. I
generally prefer boost::scoped_p tr for this but you can use
std::auto_ptr if you are careful to disable copying and assignment for
the class.

Sep 7 '06 #17
Phlip wrote:
Kai-Uwe Bux wrote:
>>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.

This piece of advice is an over-generalization. Inheritance in C++ is
orthogonal to the use of run-time polymorphism and virtual methods. In
fact, the standard library provides various templates especially designed
to be inherited that do neither provide virtual methods nor virtual
destructors; see: unary_function< or iterator<>.

That proves my point.
I does not prove your point: You claimed: "you should not inherit from a
class with no virtual methods". When you inherit from
unary_function< int,int>, you inherit from a class with no virtual methods.
Your claim implies, one should not do that. How does the example "prove
your point"?
You inherit those to use templates, not virtuals, to override methods.
You do not inherit from these classes to override methods. You can't because
these classes do not have methods. Example:

class fourier : public std::unary_func tion<double,dou ble{

unsigned long frequency;

public:

fourier ( unsigned long f )
: frequency ( f )
{}

double operator() ( double x ) const {
return ( std::sin( x * frequency ) );
}

};

This is a typical way to inherit from std::unary_func tion<double,dou bleand
one does not override any methods from the base class. The operator() is
not overridden, it is simply not present in the base class [20.3.1/1].
Your claim would imply, one should not code something like the class
fourier. Yet the standard provides templates like unary_function exactly
for this kind of use.

I simply cannot see at all how this "proves your point".

About the only reason to inherit without overriding is to create a
"convenienc e class". Sometimes, for example, the 'explicit' keyword inside
auto_ptr is annoying, so you inherit auto_ptr<myClas sto create a custom
smart pointer without it.

Actually, that proves my point too. I overrode the constructor on a
template...

Can anyone think of a convenience class that should inherit but doesn't
override something - with virtuals, templates, or some other trick?
Could you please provide a definition of the term "convenienc e class"? I
don't know what you mean. In any case, the example above inherits and no
overriding takes place at all (unless, we use the term "override"
differently).

>Your remark is firmly rooted in the OO style of programming, where it
makes
perfect sense. However, OO is but one of the various styles of
programming in C++ that make good use of inheritance. Policy based design
uses inheritance often and quite often the policy classes inherited from
will not have virtual methods.

I have misplaced my /Effective C++/ book that covers this. Could someone
be a pet and copy in the relevant quote? Scott agrees with us that in rare
cases you inherit without overriding, but in general you don't inherit to
create a "compilable comment", or "so I don't need to delegate to get to
the functions I need."
Huh? What is a "compilable comment"? Maybe I was not clear: I was talking
about policy based design as explained in Alexandrescu: Modern C++ Design.
In that context, inheritance without overrinding is not rare at all: it's
the rule not the exception.
Best

Kai-Uwe Bux
Sep 7 '06 #18
Philip Potter wrote:
No it wouldn't. It's static.
Since when do I have to read an entire paragraph before replying to it???

;-)

Back on subject, excessive return value shenanigans are a sign of Premature
Optimization. Just rely on return-value optimization, then on any
copy-on-write capacity inside the string.

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

Phlip wrote:
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.
[snip]
2. If you have virtual functions in your class, do you need a virtual
destructor? Why?
[snip]
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.
This can of course be enforced by making the destructor protected and
non virtual. Therefore, when a (base) class has virtual functions
(methods), its destructor should be either public and virtual, or
protected and non-virtual, depending on whether one intends to delete
via the applicable interface or not.

Derived classes can of course static_cast their this pointer to that of
their base and then delete themselves, but I don't think bases have to
guard agains that kind of (absurd) behaviour :-0.

[snip]

Agree, for the most.

Regards,

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

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

Similar topics

10
3105
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
9647
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
1492
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
2178
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
2347
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
9617
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10254
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...
0
10099
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
7451
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
6710
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
5354
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...
1
4007
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
2
3607
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2849
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.