-
Online C++ Test Questions
Hello Everyone, I recently gave an online C++ test. Below are few of the questions I need help with. Could anyone please explain to me the correct answers?
1) Can we call virtual function from non-virtual function?
2) Can we call pure virtual function from constructor?
3) Benefits of Templates over overriding
Code:
i) One copy of code in memory
ii) Fast
4)
Code:
Obj1 = obj2 ........... points to the same memory location?
5) Rough Code below
Code:
Class Object1; (no object created)
Class Object2 obj2; (one object created)
cout << dynamic_cast< Object1>(obj2) << endl; ....... prints what?
6) How to find a substring in a map key(syntax?), the key stores a string.
7) Returning an array from function (syntax of function signature?)
8) Default copy constructor does what
Code:
i) Reference to the original object of the same class
ii) Does nothing by default
9) Assign const pointer to a non-const pointer
Code:
i) Reinterpret
ii) Dynamic_cast
iii) Const_cast
iv) Static_cast
10) If we do not write a constructor, the compiler generates one for us. Is there a default destructor too?
11) How to print vector elements in a separate function having only a print statement
Rough Code
Code:
For_each(syntax for iteratring, printFunc) – syntax?????
For() {} – syntax?????
int printFunc(int i)
{cout << i << endl;}
12) What does double ( ## ) between two variables and single ( # ) before one variable in macros mean?
e-g ...13) Rough Code
Code:
Pointer1 ptr1 = new Pointer;
Pointer2 ptr2;
ptr2 = ptr1; ..... how to assign? Syntax
-
Re: Online C++ Test Questions
Quote:
Originally Posted by
gulHK
Hello Everyone, I recently gave an online C++ test. Below are few of the questions I need help with. Could anyone please explain to me the correct answers?
First, let's see your answers.
I know that some of the questions are worded badly, but others can be solved by just writing a simple program and testing your solution here:
http://www.compileonline.com/compile_cpp_online.php
Regards,
Paul McKenzie
-
Re: Online C++ Test Questions
Hello Paul. Below are my answers.
Thanks and Regards
1) Can we call virtual function from non-virtual function? YES
2) Can we call pure virtual function from constructor? NO (Read this answer somewhere but I don't know the reason)
3) Benefits of Templates over overloading
Code:
i) One copy of code in memory
ii) Fast (YES as it avoids pointers/polymorphism)
4)
Code:
Obj1 = obj2 ........... points to the same memory location?
5) Rough Code below
Code:
Class Object1; (no object created)
Class Object2 obj2; (one object created)
cout << dynamic_cast< Object1>(obj2) << endl; ....... prints what?
6) How to find a substring in a map key(syntax?), the key stores a string.
Code:
I know how to find a key and then extract the substring from it but is there way to do it in one step? Because the choices I remember were all ONE LINE statements - e-g find_first_of
7) Returning an array from function (syntax of function signature?)
Code:
int* foo(params) - We get a memory address pointing to the 0th element of the Array
8) Default copy constructor does what
Code:
i) Reference to the original object of the same class
ii) Does nothing by default ... FALSE b'coz then why would compiler provide one, I am still not sure of the exact reason
9) Assign const pointer to a non-const pointer
Code:
i) Reinterpret
ii) Dynamic_cast
iii) Const_cast (YES ... const_cast operator is used to add or remove a const or volatile modifier to or from a type)
iv) Static_cast
10) If we do not write a constructor, the compiler generates one for us. Is there a default destructor too? (YES)
11) How to print vector elements in a separate function having only a print statement
Rough Code
Code:
For_each(syntax for iteratring, printFunc) – syntax?????
For() {} – syntax?????
int printFunc(int i)
{cout << i << endl;}
12) What does double ( ## ) between two variables and single ( # ) before one variable in macros mean?
e-g ...13) Rough Code
Code:
Pointer1 ptr1 = new Pointer;
Pointer2 ptr2;
ptr2 = ptr1; ..... how to assign? Syntax
-
Re: Online C++ Test Questions
Quote:
Originally Posted by
gulHK
Hello Paul. Below are my answers.
Thanks and Regards
1) Can we call virtual function from non-virtual function? YES
OK. That's right.
Quote:
2) Can we call pure virtual function from constructor? NO (Read this answer somewhere but I don't know the reason)
You can call a function, but the "virtualness" will not be exhibited in the constructor. When an object is constructed, any call to a virtual function will just invoke the function as if it is non-virtual.
Quote:
3) Benefits of Templates over overloading
Code:
i) One copy of code in memory
ii) Fast (YES as it avoids pointers/polymorphism)
The simple answer is that you can write one set of generic code, and "overload" the code on a compile-time type. You can't do that with regular overloaded functions.
Quote:
4) [code]Obj1 = obj2 ........... points to the same memory location?
More information is needed. Of course if Obj1 and obj2 are pointers to a type T, then they will point to the same memory location. If Obj1 and obj2 are different objects, then they will be two distinct objects.
Quote:
5) Rough Code below
[code]Class Object1; (no object created)
Class Object2 obj2; (one object created)
There is no such keyword in C++ as Class. So the question cannot be answered.
Quote:
7) Returning an array from function (syntax of function signature?)
Code:
int* foo(params) - We get a memory address pointing to the 0th element of the Array
Don't know if this is a trick question. Your answer returns a pointer, not an array. Can you actually return an array in C++? I ask you.
Quote:
8) Default copy constructor does what
Code:
i) Reference to the original object of the same class
ii) Does nothing by default ... FALSE b'coz then why would compiler provide one, I am still not sure of the exact reason
You need to know this one, or you can be rejected by any interviewer right from the start.
The default copy constructor does a member-wise, "shallow" copy on all the individual members of the class or struct.
Quote:
11) How to print vector elements in a separate function having only a print statement
Well, this one uses a "std::copy", not "print", as there is no such function as "print" in standard C++.
Code:
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>
//...
template <typename T>
void PrintVector(const std::vector<T>& tVect)
{
std::copy(tVect.begin(), tVect.end(), std::ostream_iterator<T>(std::cout, " "));
}
int main()
{
std::vector<int> IntVector;
IntVector.push_back(10);
IntVector.push_back(20);
IntVector.push_back(30);
IntVector.push_back(40);
PrintVector(IntVector);
}
That's all I'll contribute for now.
Regards,
Paul McKenzie
-
Re: Online C++ Test Questions
4) without knowing a whole lot more about obj1 and obj2, the question cannot be answered as the operator = could be overloaded.
-
Re: Online C++ Test Questions
Quote:
Originally Posted by
2kaud
4) without knowing a whole lot more about obj1 and obj2, the question cannot be answered as the operator = could be overloaded.
Or they could be pointers. The questions aren't worded well at all.
-
Re: Online C++ Test Questions
Thank You Very Much Paul. Please have a look at the questions/answers below
4)
Code:
Obj1 and Obj2 are the Objects of the same class (type)
e-g if “Object” is the class name:
Object obj1 = new Object();
Object obj2;
Obj2 = obj1 ........... do these objects point to the same memory location?
5) Rough Code Below
Code:
Object1 and Object2 are the names of two different classes.
The Class Object2 has one Object and the Class Object1 does not have any objects
Object2 obj2 = new Object2();
cout << dynamic_cast< Object1>(obj2) << endl; ....... prints what?
7) Returning an array from function syntax
Code:
int * foo(int arr[]) … this was one of the choices given
What I learnt is that NO we cannot return an array but a pointer to the first element of the array
Code:
int * foo(int arr[]){
// populate arr
return arr;
}
int main()
{
int arrA [10];
int *arrB = foo(arrA);
for(int i=0; i<10; i++)
{
cout << arrB[i] << endl;
}
}
8) Default copy constructor does what
Code:
i) Reference to the original object of the same class
ii) Does nothing by default ... FALSE used for Object instantiation (one reason I can think of)
11) Print vector elements in a different function having only a print statement … is this correct?
Code:
for_each (myvector.begin(), myvector.end(),printVect);… this was one of the choices given
Code:
void printVect(int i) { // function for printing vector elements
std::cout << ' ' << i;
}
int main () {
std::vector<int> myvector;
// populate vector;
for_each (myvector.begin(), myvector.end(),printVect);
std::cout << '\n';
}
Can we do it with FOR LOOP?
Thanks and Regards
-
Re: Online C++ Test Questions
Quote:
4)
Code:
Obj1 and Obj2 are the Objects of the same class (type)
e-g if “Object” is the class name:
Object obj1 = new Object();
Object obj2;
Obj2 = obj1 ........... do
This is not valid c++ code. new returns a pointer which is tried to be assigned to a non-pointer instance of a class. The variable Obj2 does not exist (it should be obj2) and assuming obj1 is a pointer to an Object class, then obj2 also must be defined as a pointer variable.
Given the revised code
Code:
#include <iostream>
class Object {
public:
int a;
};
int main()
{
Object *obj1 = new Object();
Object *obj2;
obj2 = obj1;
std::cout << "address of obj1: " << obj1 << std::endl;
std::cout << "address of obj2: " << obj2 << std::endl;
}
then obj1 and obj2 do indeed point to the same memory address and hence to the same object.
-
Re: Online C++ Test Questions
Quote:
Originally Posted by
gulHK
[/code]
8) Default copy constructor does what
Code:
i) Reference to the original object of the same class
ii) Does nothing by default ... FALSE used for Object instantiation (one reason I can think of)
That is not what the answer should be. There is one universal answer, and that is to state what the default copy constructor does. I stated the answer in my previous post.
Regards,
Paul McKenzie
-
Re: Online C++ Test Questions
Thank You Very Much 2Kaud.
-
Re: Online C++ Test Questions
Thank You Very Much Paul.
-
Re: Online C++ Test Questions
Quote:
Originally Posted by
2kaud
This is not valid c++ code. new returns a pointer which is tried to be assigned to a non-pointer instance of a class. The variable Obj2 does not exist (it should be obj2) and assuming obj1 is a pointer to an Object class, then obj2 also must be defined as a pointer variable.
This is actually perfectly valid C++ assuming there is a constructor for Object that takes a Object* as parameter and that constructor isn't declared as explicit.
Granted, it's rare you'd write such a constructor (and not declare it explicit if you do, it's accidents waiting to happen).
-
Re: Online C++ Test Questions
Quote:
Originally Posted by
OReubens
This is actually perfectly valid C++ assuming there is a constructor for Object that takes a Object* as parameter and that constructor isn't declared as explicit.
Granted, it's rare you'd write such a constructor (and not declare it explicit if you do, it's accidents waiting to happen).
Yep, those assignments can be made to be legal.:o I never figured on having an Object constructor that takes as argument Object *! I'll remember that one next time I ask some newbie c++ questions:D
Code:
#include <iostream>
class Object {
public:
Object()
{
}
Object(Object*)
{
}
};
int main()
{
Object *obj1 = new Object();
Object *obj2;
Object obj3 = new Object();
Object obj4;
obj2 = obj1;
obj4 = obj3;
std::cout << "address of obj1: " << obj1 << std::endl;
std::cout << "address of obj2: " << obj2 << std::endl;
std::cout << "address of obj3: " << &obj3 << std::endl;
std::cout << "address of obj4: " << &obj4 << std::endl;
}
In this case the output is
Code:
address of obj1: 00323FF0
address of obj2: 00323FF0
address of obj3: 0012FEE0
address of obj4: 0012FEE4
which shows that obj1 and obj2 point to the same object and obj3 and obj4 point to different objects.
-
Re: Online C++ Test Questions
That's great. Thank you very much for explaining it with a practical example.
-
Re: Online C++ Test Questions
Hello everyone
Could anyone please help me with this online interview question?
Code:
Object1 and Object2 are the names of two different classes.
The Class Object2 has one Object and the Class Object1 does not have any objects
Object2 obj2 = new Object2();
cout << dynamic_cast< Object1>(obj2) << endl; ....... what does this line print?
Many Thanks
-
Re: Online C++ Test Questions
Quote:
Originally Posted by
gulHK
Hello everyone
Could anyone please help me with this online interview question?
Code:
Object1 and Object2 are the names of two different classes.
The Class Object2 has one Object and the Class Object1 does not have any objects
Object2 obj2 = new Object2();
cout << dynamic_cast< Object1>(obj2) << endl; ....... what does this line print?
Many Thanks
As previously discussed in this thread, the statement
Code:
Object2 obj2 = new Object2();
is valid if and only if Object2 has a constructor that takes a Object2* as parameter and that constructor isn't declared as explicit.
If the Object1 and Object2 classes are distinct with no relationship between them, then even assuming the obj2 assignment is correct, I doubt the dynamic_cast statement will compile and I would expect a compile error along the lines that Object2 is not polymorphic.
IMO whos ever setting these interview questions are not doing a very good job of producing understandable c++ code in the absence of class definitions! If I was given this code I would be saying that it doesn't compile - but I suspect the answer they are looking for is null (null pointer) as the dynamic_cast will fail.
See
http://msdn.microsoft.com/en-us/libr...=vs.71%29.aspx
-
Re: Online C++ Test Questions
In MSVS, this code
Code:
class Object1 {
};
class Object2 {
};
int main()
{
Object2 *obj2 = new Object2;
cout << dynamic_cast< Object1*>(obj2) << endl;
}
produces the compiler error
Quote:
error C2683: dynamic_cast : 'Object2' is not a polymorphic type
-
Re: Online C++ Test Questions
2kaud Thank You Very Very much again for explaining it with an example and in detail.
-
Re: Online C++ Test Questions
Quote:
Originally Posted by
2kaud
is valid if and only if Object2 has a constructor that takes a Object2* as parameter and that constructor isn't declared as explicit.
the "only if" part is not correct :), the ctor could take any T implicitly constructible from Object2*, hence void*,bool,...
-
Re: Online C++ Test Questions
Thank you all very much
I know that the ## (double number sign) operator concatenates two tokens in a macro invocation e-g
Code:
#define ArgArg(xyz, abc)
xyz ## abc
…………………..
Call:
ArgArg(lady, bug)
…………………..
Output:
ladybug
But I was given a question that had a # before the variable like #xyz and then ## and then #abc. I haven't seen this syntax before and have looked for it on the internet but couldn't find an answer.
Code:
#define ArgArg(xyz, abc)
#xyz ## #abc
Could you please help me with that too?
Thanks
-
Re: Online C++ Test Questions
Quote:
..have looked for it on the internet but couldn't find an answer.
You didn't look very hard! See
http://msdn.microsoft.com/en-us/library/wy090hkc.aspx
http://www.cplusplus.com/doc/tutorial/preprocessor/
# is the stringizing operator and causes the corresponding actual argument to be enclosed in double quotation marks.
This program
Code:
#define ArgArg(xyz, abc) #xyz ## #abc
#include <iostream>
int main()
{
std::cout << ArgArg(lady, bug) << std::endl;
}
prints
as the macro expansion of ArgArg expands the args to be surrounded by " (#) and then concatenated (## - token pasting operator) giving
so the cout statement compiled is
Code:
std::cout << "lady""bug" << std::endl;
which prints
as multiple string literals are effectively treated as one string
-
Re: Online C++ Test Questions
That's excellent 2Kaud .... THANK YOU SOOOO MUCH
-
Re: Online C++ Test Questions
Quote:
Originally Posted by
2kaud
IMO whos ever setting these interview questions are not doing a very good job of producing understandable c++ code in the absence of class definitions! If I was given this code I would be saying that it doesn't compile - but I suspect the answer they are looking for is null (null pointer) as the dynamic_cast will fail.
You see this kind of "tests" way too often. It's a case of either whomever is asking the questions doesn't really know C++ themselves and are just "randomly" throwing together some questions from a C++ guide or someone that's "stuck" in C++ and doesn't have the real life language skills to properly ask a question.
Half the questions here are essentially "irrelevant". because they won't really tell the interrogator what the candidate knows.
A quarter is dubious in that the question is either incomplete or downright wrong, or it assumes that the candidate knows what the interrogator is trying to achieve. It's like they picked a question out of a series of questions but in doing so lost the necessary context established in the other questions in the series.
and the rest... well... "ok", but I doubt they'll really do much good in figuring out anything about the candidate.
Unfortunately, these kind of fail-questionnaires are way too common. You don't learn much about a candidates problem solving skills by asking them trick questions about language details.
-
Re: Online C++ Test Questions
Lets analyze the questions...
1) Can we call virtual function from non-virtual function?
yes.
Question is basically irrelevant.
2) Can we call pure virtual function from constructor?
Question incomplete.
Call a PV from the constructor of the class where the PV is declared ?
from a derived class of where the PV is declared
from a non related class constructor where you're calling the PV on a member instance ?
*CAN* we call the PV in the above cases ? yes, but you may not get the result you expected.
Is just a yes/no enough
does the interrogator expect you to explain the problems with this or not ?
3) Benefits of Templates over overriding
irrelevant without context.
templates and overriding serve different purposes, so neither has an inate benefit over the other.
take any STL class, and you'll see both being used.
now. if we're talking benefit of a template over overiding for a specific function, then we may be able to say why one would be prefered/better over another. Without that specific context, any answer given can be countered by a specific case where this wouldn't be true.
as proof of this given the answers by the OP:
counter answer to 3.i: Templates can cause multiple instances of the code to be in memory (if a template is used in the exe and in dll's, and the template instance isn't exported).
counter answer to 3.ii: an override may be specifically tailored to a type and thus be faster than the generic solution in a template.
4)
question incomplete without knowing what type Object is and what constructors/operators it has or if it will even compile.
5) Rough Code below
"rough code" in a strictly typed language is asking for problems...
a) this code isn't even valid C++ and won't compile
b) are you assuming compilation with rtti or without ?
c) the rough code is incomplete because we don't know if the classes have a hierarchy relation.
d) dynamic_cast<Object1> isn't valid, it needs to be a pointer or reference, not an object type.
omision of this means we can't give an answer or do we need to answer the pointer and the reference case ?
e) it would have taken 2 minutes more effort to have fully valid, compilable, unambiguous C++ code that would have given a clear and unambiguous answer.
ignoring all of the above.
a dynamic_cast of compatible types yields the compatible type
a dynamic_cast of incompatible pointers returns a null pointer
a dynamic_cast of incompatible references throws a bad_cast exception
Now this didn't even need a rough code sample, it just needs a "What are the possible results of a dynamic_cast?" question.
6) How to find a substring in a map key(syntax?), the key stores a string.
why so vague...
A map of the world, of a specific country or city ? an std::map ? or some other map ?
I know how to find a std::string a std::map that stores a std::string as key. but how do I find a substring ? a substring of what ? of the key, of the value associated with the key in the map, is the value even a std::string ?
is substring a class we need to somehow know of?
do you just want the "std::string mysubstring mymap[mykey];" answer (seriously ? you call that even a proper question ?)
Is it ok we're assuming the above may add a new key to the map with a empty value ?
or do you want the answer where no key will be added
what answer do you want to get if the key isn't found ?
or was this a trick question and did you want the whole package answer ?
7) Returning an array from function (syntax of function signature?)
given the above vague question, and assuming array is a type we somehow have declared earlier...
array foo();
is a perfectly valid answer.
8) Default copy constructor does what
wait ? what ?
neither of the 2 answers are even close to being right.
what it does: construct an instance of a type by shallow copying it's members from the referenced type.
9) Assign const pointer to a non-const pointer
em. srsly ?
asking how it's done isn't really relevant, I'd be more concerned about the how/where/when this can be safely done in the first place.
10) If we do not write a constructor, the compiler generates one for us. Is there a default destructor too?
>.<
11) How to print vector elements in a separate function having only a print statement (Rough Code)
more rough code >.<
For_each(syntax for iteratring, printFunc) – syntax?????
iteratring ? is this something like a magic decoder ring where we need to somehow decode the silly questions into actual useful questions ?
For() ?
For_each()
I don't know how to solve either with a capital F.
12) What does double ( ## ) between two variables and single ( # ) before one variable in macros mean?
{#xyz ## #jkl}
why not give a FULL macro definition rather than these 'rough code' examples. It literally would have taken only 10sec to write this as
#define mymacro(xyz,jkl) {#xyz ## #jkl}
Yes, ask a question, then give an example that pretty much gives away the answer.
What I find strange is that this questionnaire asks questions that are "advanced" like this. and also asks silly "only been doing C++ for a week" type questions.
13) Rough Code
ARGH !!!
how to assign... em... exactly as it is in the rough example.
assuming Pointer 1 has a constructor that takes a Pointer* and Pointer2 has an assignment operator that takes a Pointer1, Pointer1& or Pointer1 has a cast operator that is compatible with a Pointer2 assignment operator.
depending on how rough the code is and what we are to assume about the types and their constructors/operators: It could be any of a couple dozen answers.
Evaluation:
I give whomever made up this questionnaire an F in C++ examination.
Whomever can answer any 3 of the above questions reasonably well should be given an A.
-
Re: Online C++ Test Questions
Quote:
Originally Posted by
OReubens
Lets analyze the questions...
I saw a supposed C++ online interview test. One of the questions was concerning "reversing a linked list", and the answer they gave was a "C" implementation of a linked list with pointer logic.
I wished I had a question asked to me like that -- I would have shown the interviewer a std::list and std::reverse() called on that list. If I received any questions on my answer, and then the interviewer shown their "C-ish" answer they had, I would respond "are you sure that your answer is correct?", and then keep insisting whether they are sure or not.
The point being that I could prove my code works all the time, while their "answer" wasn't convincing at all, and would be a candidate for someone firing up a debugger (even if eventually, the code did work) if a customer reported some sort of bug. And yes, it has happened to me in the real-world, where someone decided to go their own route instead of using std::list.
Regards,
Paul McKenzie
-
Re: Online C++ Test Questions
Quote:
Originally Posted by
OReubens
Lets analyze the questions...
Evaluation:
I give whomever made up this questionnaire an F in C++ examination.
Whomever can answer any 3 of the above questions reasonably well should be given an A.
I agree with your assessment. I'll add that tests like that are not a good way to evaluate a programmer. I had somebody who knew way more obscure syntax than I do, but couldn't figure out how to program an arithmetic mean or a standard deviation. You need to know the rules, but a test like that tells you nothing about how good a programmer is. Programming is way more about how you approach and solve a problem than it is how many dark corners of the language you know.
-
Re: Online C++ Test Questions
Quote:
Originally Posted by
GCDEF
I agree with your assessment. I'll add that tests like that are not a good way to evaluate a programmer.
This is especially the case with C++, since it is such a large language with a lot of rules that anyone could miss them (save for the usual "what is a destructor, constructor, purpose of copy constructor", type questions).
And if you aren't familiar with the rule but happen to be a good to excellent programmer, how long would it take such a programmer to use google to figure out how to use a certain language feature? A minute? So an interviewer would reject someone who, in a minute or less, would know how to use whatever they were not sure of? It's really stupid.
Now that there are even more features to the language with the new C++ 11, the "ask an obscure question" type of interview becomes even more useless.
Regards,
Paul McKenzie
-
Re: Online C++ Test Questions
Personally... I wouldn't care (much) if the guy answers a question with a code sample that has minor syntax errors. **WE** aren't compilers afterall and a simple compile of the code would reveal the syntax errors anyway.
Knowing how/why certain things are (best) done in a certain way. And askign questions that will reveal how much experience the guy has had with actual programming, and whether they have the mental ability to quickly analyze a problem and turn that into a working piece of code is much more relevant than any of the above questions.
for the most part, you don't even need to know much about the "funky/murky" rules in c++, more often than not it's better to entirely avoid those shady areas altogether and write code that doesn't depend on them.
simple code where each statement does one thing is better than huge compound statements that do a bazillion things if you can figure out what happens in which order under what condition.