473,770 Members | 1,973 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
Kai-Uwe Bux wrote:
>And C++ is multi-paradigm, so within the template paradigm, you should
not
inherit except to specialize a member.

The fourier example did not do that. Generally, when inheriting from
unary_function you will not specialize any of the members of
unary_function.
That's why I wrote "operator()...m ight not exist in the parent":
>Your example "overrode" operator(). I am aware it was not virtual, and
might not exist in the parent.

You are using the term "override" strangely.
And that's why I wrote "very similar to an override":
>Yet what you did was very similar to an override, from the caller's point
of view.
--
Phlip
http://www.greencheese.us/ZeekLand <-- NOT a blog!!!
Sep 8 '06 #31

Kai-Uwe Bux wrote:
I see, you generalized your position to: one should not inherit unless one
overrides something (virtual or not) or adds something (which is what you
call overriding with quotation marks). In other words, one should not do

class X : public y {
...
}

unless X behaves at least a little different from Y. Well, I might grant you
that. However, In my eyes,
Well, that would not exactly help with regard to template programming.
For instance one couldn't do something like this:

template < typename D, typename U >
struct unit : dimension_type< D>, convertable<U>. ..
{
};

struct seconds : unit<time_d, seconds{};
double const seconds::cvf::v alue = 1.0;

"seconds" doesn't add any behavior to the unit type (unless you
consider different conversion values an extension) and the unit type
adds nothing to its parents beyond the conglomeration of various
parents' features into one type. However, a decent syntax for creating
new unit types has been created and these static types can be used in
template programming in unit based dimensional analysis and custom
printing:

template < typename U >
struct unit_printer {}

template <>
struct unit_printer<se conds>
{
std::string operator () () { return "s"; }
};

So there can be numerous reasons to subclass something but not extend
it and with MI you can be extending simply through inheritance.

And it's Friday and I'm particularly out of it today or I'd give a
better argument but I think that saying, "never inherit without
extending or changing behavior," as a rule can be very limiting in many
aspects of C++ programming. It also seems to be less than accurate as
you can extend at least without inheriting. The more narrow guideline
given by Sutter and Myers (don't inherit unless you need to override
some polymorphic function) is more to the point but still fails in
light of certain idioms in generic programming where inheritance isn't
necissarily used according to the standard OO definition. For
instance, such a guideline would say never do the above, and maybe it
really isn't the best way to do what I want, but there is no reason not
to when your parents exist solely for the purpose of generating new
static types without having to type the same things repeatedly and/or
provide special compile time functionality to test types and compile in
different behavior based on the inherited metafunction members.

Sep 8 '06 #32
Noah Roberts wrote:
And it's Friday and I'm particularly out of it today or I'd give a
better argument but I think that saying, "never inherit without
extending or changing behavior," as a rule can be very limiting in many
aspects of C++ programming. It also seems to be less than accurate as
you can extend at least without inheriting. The more narrow guideline
given by Sutter and Myers (don't inherit unless you need to override
some polymorphic function) is more to the point but still fails in
light of certain idioms in generic programming where inheritance isn't
necissarily used according to the standard OO definition.
The most general way to say it is "prefer weak coupling to strong coupling".
Delegation is weak, and the various forms of inheriting and specializing are
strong. Don't do it unless you get a benefit, and that benefit often appears
as an "override" of some kind.
For
instance, such a guideline would say never do the above, and maybe it
really isn't the best way to do what I want, but there is no reason not
to when your parents exist solely for the purpose of generating new
static types without having to type the same things repeatedly
If that is a "convenienc e class", then at least you _know_ that it is. You
are not going down the path of inheritance as an arbitrary form of
categorization, without any design value.
and/or
provide special compile time functionality to test types and compile in
different behavior based on the inherited metafunction members.
"different behavior" is the meaning of the "override" in the original
admonition.

--
Phlip
http://www.greencheese.us/ZeekLand <-- NOT a blog!!!
Sep 8 '06 #33

Phlip wrote:
Noah Roberts wrote:
and/or
provide special compile time functionality to test types and compile in
different behavior based on the inherited metafunction members.

"different behavior" is the meaning of the "override" in the original
admonition.
However, in this case the "different behavior" is based on members that
are inherited, not overridden. For instance one might have the
following:

struct seconds : unit<time_d, seconds>, unit_is_static< seconds, true>
{};

template < typename U, bool is_static >
struct unit_is_static;

template <typename U>
struct unit_is_static< U, false{ struct is_static :
boost::mpl::boo l_<false{}; };

template <typename U>
struct unit_is_static< U, true{
struct is_static : boost::mpl::boo l_<true{};
static U const value;
};

template <typename U>
U const unit_is_static< U, true>::value = U(); // necissary to access
double conversion

Now later you could very concievably use mpl::if_ based on the
"is_static" metafunction member. That member is an inherited member so
behavior doesn't change based on differences in the derived class but
by which class it inherits from.

Sep 8 '06 #34
Noah Roberts wrote:
Now later you could very concievably use mpl::if_ based on the
"is_static" metafunction member. That member is an inherited member so
behavior doesn't change based on differences in the derived class but
by which class it inherits from.
Another important point is we are all discussing design at a level much
higher than the newbies who need to be taught "don't inherit unless you then
override a virtual method"... ;-)

--
Phlip
http://www.greencheese.us/ZeekLand <-- NOT a blog!!!
Sep 8 '06 #35

Phlip wrote:
Noah Roberts wrote:
Now later you could very concievably use mpl::if_ based on the
"is_static" metafunction member. That member is an inherited member so
behavior doesn't change based on differences in the derived class but
by which class it inherits from.

Another important point is we are all discussing design at a level much
higher than the newbies who need to be taught "don't inherit unless you then
override a virtual method"... ;-)
Actually I think that some of the paradigms and idioms beyond OO should
be taught to new C++ programmers. Concepts like policies are very
useful but unfortunately not taught in any class I am aware of. Hell,
the concept of a concept was never taught to me and this seems rather
fundamental in anything remotely interesting in C++.

Sep 8 '06 #36
Phlip wrote:
Noah Roberts wrote:
>Now later you could very concievably use mpl::if_ based on the
"is_static" metafunction member. That member is an inherited member so
behavior doesn't change based on differences in the derived class but
by which class it inherits from.

Another important point is we are all discussing design at a level much
higher than the newbies who need to be taught "don't inherit unless you
then override a virtual method"... ;-)
Newbies do not need to be lied to :-) Your sound piece of advice would be
more helpful to newbies if it came with appropriate qualification: "in OO
design, don't inherit unless you then override a virtual method." You do
not help newbies by giving advice that is implicitly biased toward one of
the various paradigms supported by C++. That way you would be narrowing the
perspective of the newbies on C++ instead of opening up their view.
Best

Kai-Uwe Bux
Sep 8 '06 #37
Kai-Uwe Bux wrote:
Newbies do not need to be lied to :-) Your sound piece of advice would be
more helpful to newbies if...
You have a typo there. You were trying to write "Scott Meyers's, Herb
Sutter's, and Andrei Alexandrescu's advice would be helpful to newbies..."

--
Phlip
http://www.greencheese.us/ZeekLand <-- NOT a blog!!!
Sep 8 '06 #38
Phlip wrote:
Kai-Uwe Bux wrote:
>Newbies do not need to be lied to :-) Your sound piece of advice would be
more helpful to newbies if...

You have a typo there. You were trying to write "Scott Meyers's, Herb
Sutter's, and Andrei Alexandrescu's advice would be helpful to newbies..."
Your appeal to authority is well taken. However, should you mean to imply
that, say, Alexandrescu has given that advice of yours without
qualification somewhere in his writings, I would (a) ask for an actual
quote, and (b) should you be able to provide one, maintain, that he slipped
there. However, from his writings I have read, I would be very surprised if
he actually stated an unqualified oversimplificat ion like "do not inherit
unless you override a virtual function".
Best

Kai-Uwe Bux
Sep 9 '06 #39

Stuart Redmann wrote:
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.

Thank you for the excellent example above. The output I
get is that for B, the initialisation contructor is called,
whereas for C, the default constructor is called, followed
by a call to the assignment operator function.

This is a bit puzzling for the case of B. I thought that before
B's constructor is entered, all of B's member variables must
have already been constructed, meaning that A's
default constructor should have already been called.
Is this not the case when an initialisation list is
present that uses a member variable?

Sep 9 '06 #40

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
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
10036
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
9904
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
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.

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.