Dare to test your C++ knowledge here?

22b3033832c5c699c856814b0cf80cb1
0
bladder 101 Oct 28, 2004 at 12:09

Try and do this without referencing anything to see how much you really know about c++. 18 questions all together. none of them have answers more the a line or two.

NOTE: If you don’t want any of the answers spoilt, then answer them in a notepad or something before scrolling through the replies.

Q 000) What's the difference between 'char* = "blah"' and 'char[] = "blah"'?

Q 001) What does koenig look-up allow us to do?

Q 002) Give an example of partial ordering of function templates.

Q 003) What is placement new?

Q 004) When is placement delete used?

Q 005) What's the maximum value x can contain?

 unsigned int x:5;

Q 006) What will the following display?

 short x = -32768;
 short y = -x;
 if( x != y ) std::cout << "!="<< std::endl;
 else std::cout<< "=="<< std::endl;

Q 007) When does the following evaluate to true?

 if( x == x == x )

Q 008) When does the following evaluate to true?

 if( x != x != x )

Q 009) What will be the value of x?

 int x = 2;
 x += x++;

Q 010) What does the follwoing print?

 std::cout<< ( 4 >= 3 >= 2 )<< std::endl;
 std::cout<< ( 2 >= 1 >= 0 )<< std::endl;

Q 011) How do you invoke the ctor and dtor explicitly?

Q 012) Will std::vector always have contigious memory?

Q 013) What is template specialization and partial specialization?

Q 014) Rewrite the following function so that the following conditions are satisfied:
    A) the multiplication operator ('*') is not used.
    :) the division operator ('/') is not used.
    C) the function does not make use of loops.
    D) And no using assembly either

 int MultiplyBy321(int val)
 {
  int res;
  res = val * 321;
  return res;
 }

Q 015) Determine if a given type T is const or not at compile time.

Q 016) What is the purpose of inheritance?

Q 017) How would you load a text file on disk into memory?

Q 018) What does the following macro do?

 #define macro(x, y) (int)(&((x*)0)->y)

REMEMBER: DO NOT scroll past this point if you dont want to see the answers to some questions.

31 Replies

Please log in or register to post a reply.

99f6aeec9715bb034bba93ba2a7eb360
0
Nick 102 Oct 28, 2004 at 12:48

What can we win? :D Should we send you a private message or spoil the answers?

22b3033832c5c699c856814b0cf80cb1
0
bladder 101 Oct 28, 2004 at 13:27

what you win is the satisfaction that you are one with the force…err…i mean with c++. And yeah by all means just post the answers the them right here. Ill edit my above post and tell people not to scroll down if they don’t want to see any answers.

8563f7b73aeb34bb8604f1dd8f546c88
0
Mattias_Gustavsson 101 Oct 28, 2004 at 14:04

@bladder

Q 018) What does the following macro do?

  #define macro(x, y) (int)(&((x*)0)->y)

Make the code harder to read? :rolleyes:

0d69890e5c3b4a6aac320f40026314b1
0
pecina 101 Oct 28, 2004 at 14:52

@Mattias Gustavsson

@bladder

Q 018) What does the following macro do?

  #define macro(x, y) (int)(&((x*)0)->y)

Make the code harder to read? :)

[snapback]13397[/snapback]

Returns an offset of var from begging of class.

struct vector {
float x, y
};

macro(vector, x) will return 0 and
macro(vector, y) will return 4

065f0635a4c94d685583c20132a4559d
0
Ed_Mack 101 Oct 28, 2004 at 15:32
Q 014) Rewrite the following function so that the following conditions are satisfied:
    A) the multiplication operator ('*') is not used.
    B) the division operator ('/') is not used.
    C) the function does not make use of loops.
    D) And no using assembly either

 int MultiplyBy321(int val)
 {
  int res;
  res = val * 321;
  return res;

Is this an acceptable answer?

template <unsigned N> struct _MultiplyBy321
{
 enum { Answer = 321 + _MultiplyBy321<N-1>::Answer };
};
                                        
template <> struct _MultiplyBy321 <1>
{
 enum { Answer = 321 };
};
                                        
/* Somewhere else: */
#define MultiplyBy321(x) _MultiplyBy321<x>::Answer

(I had to use reference when it wouldn’t compile, sorry :( )

2b97deded6213469bcd87b65cce5d014
0
Mihail121 102 Oct 28, 2004 at 16:21

@bladder

Q 014) Rewrite the following function so that the following conditions are satisfied:
    A) the multiplication operator ('*') is not used.
    B) the division operator ('/') is not used.
    C) the function does not make use of loops.
    D) And no using assembly either

 int MultiplyBy321(int val)
 {
  int res;
  res = val * 321;
  return res;
 }

REMEMBER: DO NOT scroll past this point if you dont want to see the answers to some questions.

[snapback]13392[/snapback]

Ok, i have a recursive add solution but someone might say it’s a form of loop. Anyway, here it goes:

int MulBy321(int val) {
  return RecAdd(321, val);
}

int RecAdd(int num, int val) {
  if (!num)
    return 0;
  
  return val + RecAdd(num - 1, val);
}

void main() {
 printf("9 * 321 = %d", MulBy321(9));
}
6ad5f8c742f1e8ec61000e2b0900fc76
0
davepermen 101 Oct 28, 2004 at 16:39

321 = 256 + 64 + 1 =>

x*321 = x*256 + x*64 + x

=>

x*321 = x<<8 + x<<5 + x

thats the “lowlevel answer”

99f6aeec9715bb034bba93ba2a7eb360
0
Nick 102 Oct 28, 2004 at 16:50

@bladder

Q 001) What does koenig look-up allow us to do?

Nothing that we couldn’t before. :cool:

Koenig was just lazy… that’s why we love him!

2b97deded6213469bcd87b65cce5d014
0
Mihail121 102 Oct 28, 2004 at 16:51

Isn’t shift exactly kind of multiply operator? Oh damn, if you are going to give questions be more specific, ok?

99f6aeec9715bb034bba93ba2a7eb360
0
Nick 102 Oct 28, 2004 at 17:03

@bladder

Q 006) What will the following display?  short x = -32768;
 short y = -x;
 if( x != y ) std::cout << “!=”<< std::endl;
 else std::cout<< “==”<< std::endl;

-32768 == -32768

It’s the biggest negative value a short can hold. But 32767 is the biggest positive number so 32768 has no positive. The result can be found by negating all bits of 0x8000 and adding 1 (the equivalent of a negation). Which is again 0x8000 or -32768.

99f6aeec9715bb034bba93ba2a7eb360
0
Nick 102 Oct 28, 2004 at 17:16

@bladder

Q 011) How do you invoke the ctor and dtor explicitly?

Forget all about Koenig. :D

Here’s an extra question: How to get a pointer to a constructor? Don’t take the question too literal, solve the problem.

22b3033832c5c699c856814b0cf80cb1
0
bladder 101 Oct 28, 2004 at 19:17

@Ed Mack

Is this an acceptable answer?
(I had to use reference when it wouldn’t compile, sorry :( )

Yeah I suppose that’s acceptable. Not really a function though, it’s a macro. Since you were already on the recursive bandwagon you might as well just have done this:

int MultiplyBy321( int x )
{
  if( x == 1 ) return 321;
  else return MultiplyBy321(x-1) + 321;
}

But templates are always fun eh ;)

@Mihail121

Ok, i have a recursive add solution but someone might say it’s a form of loop. Anyway, here it goes:

Yeah that works. loops would just include while/for/do/(i suppose some may say goto and label would also be a loop, but whatever…).
@davepermen

321 = 256 + 64 + 1 =>

x*321 = x*256 + x*64 + x

=>

x*321 = x<<8 + x<<5 + x

thats the “lowlevel answer”

It’s actually x << 8 + x << 6 + x. Maybe you just hit 5 instead of 6 but yeah, that’s the answer I was expecting :)
@Mihail121

Isn’t shift exactly kind of multiply operator? Oh damn, if you are going to give questions be more specific, ok?

If you are going to answer questions then read the question first. I said dont use the “multiplication operator”. I didn’t say dont multiply. But either way, shift is not *exactly* a multiply operator. It’s more of a subset of the multiply operator - ie: only multiply by powers of two.
@Nick

Here’s an extra question: How to get a pointer to a constructor? Don’t take the question too literal, solve the problem.

Nice one! You cant get a direct pointer to the class constructor. apparently msvc is not letting me do what I want again (compiler error C2277) :). But Im guessing that placement new is going to come in handy for this one. a pointer to a function that calls placement new or something. Can you get a pointer to placement new??? That would *technically* be a pointer to the ctor…

Going to try now.

If people got more questions, bring em on :) this is fun.

46407cc1bdfbd2db4f6e8876d74f990a
0
Kenneth_Gorking 101 Oct 28, 2004 at 19:26

@Nick

@bladder

Q 011) How do you invoke the ctor and dtor explicitly?

Forget all about Koenig. :D

Here’s an extra question: How to get a pointer to a constructor? Don’t take the question too literal, solve the problem.

[snapback]13409[/snapback]

That’s kids stuff. This is for real men!

(Script->*script_t::vftable[*Code++])(Frame);
46407cc1bdfbd2db4f6e8876d74f990a
0
Kenneth_Gorking 101 Oct 28, 2004 at 19:32

No it’s not! What the hell am i doing?!?

22b3033832c5c699c856814b0cf80cb1
0
bladder 101 Oct 28, 2004 at 19:34

@Kenneth Gorking

That’s kids stuff. This is for real men!

(Script->*script_t::vftable[*Code++])(Frame);

[snapback]13412[/snapback]

Dude! Some of us are working in the AM without coffee y’know :)

But Id say that that piece of code is calling a bunch of virtual function in the class script_t. Code is an array of the indices of where the function addresses are stored in vftable. And Frame would simply be the standard parameter that all the functions accept.

46407cc1bdfbd2db4f6e8876d74f990a
0
Kenneth_Gorking 101 Oct 28, 2004 at 19:46

It’s not virtual functions, but a static array of opcodes supported by my virtual machine, and Code is simply the bytecode dereferenced to give the index to the opcode to execute. Frame is the script execution frame, which holds the call- and variablestack.
The ‘*script_t::vftable[*Code++]’ is just the opcode dereferenced, and the ‘Script->’ infront of it is the context in which it is executed.

E26db8686cae4ec080e0c9e4c2d18676
0
knackered3 101 Oct 28, 2004 at 19:52

jesus, this is the equivalent to the theme of carving chess pieces in the Shawshank Redemption.
Don’t you people have better things to do?
Program some actual stuff…get a job….get a life. Heck, carve some chess pieces.

065f0635a4c94d685583c20132a4559d
0
Ed_Mack 101 Oct 28, 2004 at 20:03

I started self learning C++ this summer, and it’s really interesting reading all this :) I tried to get Herbert Schild (sp?)’s C++ ref, as I loved the C version, but my hopeless bookshop didn’t stock it (I had gift vouchers for there). It’s now on the Amazon Christmas cart :). Is it a good / the best reference book for covering the whole basic language?

22b3033832c5c699c856814b0cf80cb1
0
bladder 101 Oct 28, 2004 at 20:17

@Nick

Here’s an extra question: How to get a pointer to a constructor? Don’t take the question too literal, solve the problem. [snapback]13409[/snapback]

Got something. Not very fun to execute though…

#include <iostream>
using namespace std;

class Class
{
public:
  int x;

  Class() {
    x = 3;
  }

  void* operator new (size_t sz, void* p)
  {
    return ::new(p) Class();
  }
};

void main()
{
  void* (*ctor)(size_t, void*) = Class::operator new;

  Class* c = (Class*)malloc(sizeof(Class));

  cout<< c->x<< endl;
  
  ctor(sizeof(Class), c);

  cout<< c->x<< endl;

  free(c);
}

[edit]
doh!
Might as well just use a static function instead of overriding the new op.
void* (*ctor)(Class*) = Class::FunctionThatCallsPlacementNew;
ctor( c );
[/edit]

Fdbdc4176840d77fe6a8deca457595ab
0
dk 158 Oct 28, 2004 at 20:19

I like the questions. Some of them make good interview questions :)

Fdbdc4176840d77fe6a8deca457595ab
0
dk 158 Oct 28, 2004 at 20:44

Here’s some other good questions you can add to the list:

Q1) What is the difference between the following declarations:

const char *a
char const *a
char* const a;


Q2) If you have a base class and another class derived from the base. When calling a
 virtual function from the contructor, why does base ctor get the base's virtual function
 instead of the derived version?

Q3) When and why would you want to declare a virtual destructor?
99f6aeec9715bb034bba93ba2a7eb360
0
Nick 102 Oct 28, 2004 at 22:17

@bladder

Got something. Not very fun to execute though…

The answer is really simple. Almost trivial actually. My question was to get a pointer to a constructor. Taking the definition of ‘constructor’ liberally, I just want a function that creates an object. The simplest way to do this is to have a static function like this:

class Foo
{
  Foo()
  {
    // Hello world!
  }
};

static Foo *fooConstructor()
{
  return new Foo();
}

fooConstructor can be used as a pointer, passed around to create the object we want without keeping track of the actual type of object we need. I don’t recommend this approach if you can avoid it though. I once had to use it to construct an object from assembly code. I searched for several days how to get the pointer of the constructor into the assembly code, until I realized how simple it was…

22b3033832c5c699c856814b0cf80cb1
0
bladder 101 Oct 29, 2004 at 02:53

@Dia Kharrat

Here’s some other good questions you can add to the list:

Q1) What is the difference between the following declarations:

const char *a
char const *a
char* const a;


Q2) If you have a base class and another class derived from the base. When calling a
 virtual function from the contructor, why does base ctor get the base's virtual function
 instead of the derived version?

Q3) When and why would you want to declare a virtual destructor?

[snapback]13423[/snapback]

Q1) const char* is a pointer to constant data; char const* is also a pointer to “char const” ie: to constant data. Thrid one is a constant pointer to data (data can be changed but not pointer).

Q2) Because the derived class hasnt been created yet?

Q3) If you have the following situation
Renderer* r = new D3DRenderer();
delete r;

If you want r\~D3DRenderer to be called then \~Renderer better be virtual.

A8433b04cb41dd57113740b779f61acb
0
Reedbeta 167 Oct 29, 2004 at 03:52

Interesting thread. Some of these questions are obvious, some abtruse…

Q 000) What’s the difference between ‘char* = “bah”’ and ‘char[] = “blah”’?

Besides the difference between “blah” and “bah”? I’m guessing that the second one is not null-terminated, am I right?

Q 005) What’s the maximum value x can contain?

unsigned int x:5;

My guess is 31. The ‘:5’ limits it to using 5 bits, correct?

Q 018) What does the following macro do?

#define macro(x, y) (int)(&((x*)0)->y)

That’s kinda cool, actually..

22b3033832c5c699c856814b0cf80cb1
0
bladder 101 Oct 29, 2004 at 05:51

sorry ReedBeta, the blah thing was a typo. It’s fixed now.

But as for your answer, no, they are both null terminated. The difference is that char[] allocated memory for ‘x’ number of characters (5 in this case) whereas char* just allocated memory to store a pointer, and *assumes* that it points to a valid string of characters. Furthermore, char[] does not point to const data and is more solid then char*. char* may point to const data, or it may not.

for example try doing this:

char a[] = “blah”;
char* b = “blah”;

strcpy( a, “halb” ); // will not crash
strcpy( b, “halb” ); // most probably will crash.

My guess is 31. The ‘:5’ limits it to using 5 bits, correct?

correct.

3a53830bbb3936338554ddf7a72b5e75
0
cdgray 101 Aug 29, 2005 at 04:43

This is an excellent thread. Learned a lot by reading it :)

0684f9d33f52fa189aad7ac9e8c87510
0
baldurk 101 Aug 29, 2005 at 09:13

@cdgray

This is an excellent thread. Learned a lot by reading it :) [snapback]20440[/snapback]

Don’t post to topics that are almost a year old unless you have a really good reason. Saying you enjoyed the thread isn’t.

340bf64ac6abda6e40f7e860279823cb
0
_oisyn 101 Sep 02, 2005 at 10:33

Don’t want to kick this thread, but since it’s done already and not all the answers are posted yet, here’s my list:

Q 000) The first defines a pointer to some statically allocated buffer, the second defines an array of 5 chars in the current scope.

Q 001) Use functions (primarily used for operators) defined in the same namespace as the type you use the operators on. Without koenig look-up, this wouldn’t work:

#include <iostream>
#include <string>

int main ()
{
  std::string blah ("blah");
  std::cout << blah;
}

because the operator << (ostream &, const string &) is defined in the std namespace, and you’re not explicitely importing everything from the std namespace into the global namespace using a using directive (using namespace std;)

Q 002)

template<class T> void foo(T * t);   // #1
template<class T> void foo(const T * t); // #2

int main()
{
  const int i = 3;
  foo(i); // calls #2 with T=int -not #1 with T=const int- because it is more specialized
}

Q 003) While primarily used to construct an object in a given piece of memory using a void * as second argument to new, it is practically any defined new operator with more than 1 parameter

char buf[sizeof(MyClass)];
new (buf) MyClass (123); // constructs a MyClass inside buf.

Q 004) It is called when the constructor throws an exception when constructed using a placement new operator

Q 005) 31

Q 006) Depends on the actual bitsize of short so this question is unanswerable, but assuming it’s 16 it will output “==” and a newline.

Q 007) Nittpick answer: an incomplete if statement evaluates to nothing but a compile error :D

Serious answer: When x is some value type that evaluates to 1 or true (or when x is of some type T for which operator==(T, T) and operator==(bool, T) are defined and the latter returns true for some value of x ;))

Q 008) I’ll ignore the custom types for x for now, x can be anything but a value that evaluates to 0 or false.

Q 009) Undefined.

Q 010) “0”, followed by a newline, followed by “1”, followed by a newline.

Q 011) By using a placement new and an explicit destructor call:

MyClass * c = new (buffer) MyClass;
c->~MyClass();

Q 012) Yes.

Q 013) A template specialization is a specialization of a template for a specific set of template parameter values. Partial specialization is a form of template specialization where a class (or struct) is specialized but not for a complete set of explicit template parameters.

template<class T> struct MyType { };
template<class T> struct MyType<T *> { }; // partial specialization for all pointers
template<> struct MyType<bool *> { }; // explicit specialization for bool*

Q 014)

int MultiplyBy321(int val)
{
  return (val << 8) + (val << 6) + val;
}

Q 015)

template <class T> struct TypeTraits
{
  static const bool isConst = false;
  // you probably want more definitions here
};

template<class T> struct TypeTraits<const T>
{
  static const bool isConst = true;
};

template<class T> void foo()
{
  if (TypeTraits<T>::isConst)
    std::cout << "T is const" << std::endl;
  else
    std::cout << "T is not const" << std::endl;
}

Or you could use the TypeTraits<T>::isConst as a template parameter to do more compile-time logic.

Q 016) Polymorphism, defining a derived type with more specialized functionality. Because a derived class inherits everything from it’s base, it can be seen as a base.

Q 017)

std::ostringstream output;
std::ifstream input ("file.txt");
output << input.rdbuf();

output.str() now returns a std::string with the contents of the file, assuming everything worked out fine (you should check for errors on input)

Q 018) It returns the offset of a member in a struct/class. Note that this doesn’t work if y is a bitfield or a type with an operator & that doesn’t what you expect.

49d03f4858f16c002c085a615130fdd1
0
edam 101 May 30, 2012 at 14:21

@.oisyn

Q 009) Undefined.

Why is

int x = 2;
x += x++;

Why is the value of x undefined, exactly? Isn’t this defined by operator precendence?

340bf64ac6abda6e40f7e860279823cb
0
_oisyn 101 May 30, 2012 at 18:50

Operator precedence has nothing to do with evaluation order, and evaluation order is undefined inbetween sequence points. The problem with that particular expression is whether the new value of x after the increment is written before or after the assignment. Both are perfectly acceptable according to the C++ standard. The resulting value of x can be 3 or 5, depending on compiler implementation:

int x = 2;
int tmp = x;
x = tmp + 1;
x += tmp;   // x == 5

// or

int x = 2;
int tmp = x;
x += tmp;
x = tmp + 1;  // x == 3
8676d29610e6c98d6dd2d9c38528cd9c
0
alphadog 101 Jun 01, 2012 at 13:43

@bladder

Try and do this without referencing anything to see how much you really know about c++. 18 questions all together. none of them have answers more the a line or two.

The funny (sad?) thing about a quiz like that is that you can find people who can answer all these didactic questions, yet still would not be able to code their way out of a box.