Monday, March 24, 2008

C++ notes for discussion @ Tech Interviews.com

C++ notes for discussion @ Tech Interviews.com

This is not really a set of interview questions, a reader sent TechInterviews.com what looks like a copy of his notes from C++ class that describes various tricks and code for C++.

  1. What is the output of printf(“%d”)?
    1. %d helps to read integer data type of a given variable
    2. when we write (“%d”, X) compiler will print the value of x assumed in the main
    3. but nothing after (“%d”) so the output will be garbage
    4. printf is an overload function doesnt check consistency of the arg list – segmentation fault
  2. What will happen if I say delete this? - destructor executed, but memory will not be freed (other than work done by destructor). If we have class Test and method Destroy { delete this } the destructor for Test will execute, if we have Test *var = new Test()
    1. pointer var will still be valid
    2. object created by new exists until explicitly destroyed by delete
    3. space it occupied can be reused by new
    4. delete may only be applied to a pointer by new or zero, applying delete to zero = no FX
    5. delete = delete objects
    6. delete[] – delete array
    7. delete operator destroys the object created with new by deallocating the memory assoc. with the object
    8. if a destructor has been defined fir a class delete invokes that desructor
  3. Difference between C structure and C++ structure - C++ places greater emphasis on type checking, compiler can diagnose every diff between C and C++
    1. structures are a way of storing many different values in variables of potentially diff types under under the same name
    2. classes and structures make program modular, easier to modify make things compact
    3. useful when a lot of data needs to be grouped together
    4. struct Tag {…}struct example {Int x;}example ex; ex.x = 33; //accessing variable of structure
    5. members of a struct in C are by default public, in C++ private
    6. unions like structs except they share memory – allocates largest data type in memory - like a giant storage: store one small OR one large but never both @ the same time
    7. pointers can point to struct:
    8. C++ can use class instead of struct (almost the same thing) - difference: C++ classes can include functions as members
    9. members can be declared as: private: members of a class are accessible only from other members of their same class; protected: members are accessible from members of their same class and friend classes and also members of their derived classes; public: members are accessible from anywhere the class is visible
    10. structs usually used for data only structures, classes for classes that have procedures and member functions
    11. use private because in large projects important that values not be modified in an unexpected way from the POV of the object
    12. advantage of class declare several diff objects from it, each object of Rect has its own variable x, y AND its own functions
    13. concept of OO programming: data and functions are properties of the object instead of the usual view of objects as function parameters in structured programming
  4. Difference between assignment operator and copy constructor - -assignment operator = assigning a variable to a value - copy constructor
    1. constructor with only one parameter of its same type that assigns to every nonstatic class member variable of the object a copy of the passed object
    2. copy assignment operator must correctly deal with a well constructed object - but copy constructor initializes uninitialized memory
    3. copy constructor takes care of initialization by an object of the same type x
    4. for a class for which the copy assignment and copy constructor not explicitly declared missing operation will be generated by the compiler. Copy operations are not inherited - copy of a class object is a copy of each member
    5. memberwise assignment: each member of the right hand object is assigned to the corresponding member of the left hand object
    6. if a class needs a copy constructor it will also need an assignment operator
    7. copy constructor creates a new object, assignment operator has to deal w/ existing data in the object
    8. assignment is like deconstruction followed by construction
    9. assignment operator assigns a value to a already existing object
    10. copy constructor creates a new object by copying an existing one
    11. copy constructor initializes a freshly created object using data from an existing one. It must allocate memory if necessary then copy the data
    12. the assignment operator makes an already existing object into a copy of an existing one.
    13. copy constructor always creates a new object, assignment never does
  5. Difference between overloading and overriding?
    1. Overload - two functions that appear in the same scope are overloaded if they have the same name but have different parameter list
    2. main() cannot be overloaded
    3. notational convenience - compiler invokes the functions that is the best match on the args – found by finding the best match between the type of arg expr and parameter
    4. if declare a function locally, that function hides rather than overload the same function declared in an outer scope
    5. Overriding - the ability of the inherited class rewriting the virtual method of a base class - a method which completely replaces base class FUNCTIONALITY in subclass
    6. the overriding method in the subclass must have exactly the same signature as the function of the base class it is replacing - replacement of a method in a child class
    7. writing a different body in a derived class for a function defined in a base class, ONLY if the function in the base class is virtual and ONLY if the function in the derived class has the same signature
    8. all functions in the derived class hide the base class functions with the same name except in the case of a virtual functions which override the base class functions with the same signature
  6. Virtual
    1. single most important feature of C++ BUT virtual costs
    2. allows derived classes to replace the implementation provided by the base class
    3. without virtual functions C++ wouldnt be object oriented
    4. Programming with classes but w/o dynamic binding == object based not OO
    5. dynamic binding can improve reuse by letting old code call new code
    6. functions defined as virtual are ones that the base expects its derived classes to redefine
    7. virtual precedes return type of a function
    8. virtual keyword appears only on the member function declaration inside the class
    9. virtual keyword may not be used on a function definition that appears outside the class body
    10. default member functions are nonvirtual
  7. Dynamic Binding
    1. delaying until runtime the selection of which function to run
    2. refers to the runtime choice of which virtual function to run based on the underlying type of the object to which a reference or a pointer is based
    3. applies only to functions declared as virtual when called thru reference or ptr
    4. in C++ dynamic binding happens when a virtual function is called through a reference (|| ptr) to a base class. The face that ref or ptr might refer to either a base or a derived class object is the key to dynamic binding. Calls to virtual functions made thru a reference or ptr are resolved at run time: the function that is called is the one defined by the actual type of the object to which the reference or pointer refers
  8. Explain the need for a virtual destructor
    1. destructor for the base parts are invoked automatically
    2. we might delete a ptr to the base type that actually points to a derived object
    3. if we delete a ptr to base then the base class destructor is run and the members of the base class are cleared up. If the objectis a derived type then the behavior is undefined
    4. to ensure that the proper destructor is run the destructor must be virtual in the base class
    5. virtual destructor needed if base pointer that points to a derived object is ever deleted (even if it doesnt do any work)
  9. Rule of 3
    1. if a class needs a destructor, it will also need an assignment operator and copy constructor
    2. compiler always synthesizes a destructor for us
    3. destroys each nonstatic member in the reverse order from that in which the object was created
    4. it destroys the members in reverse order from which they are declared in the class1. if someone will derive from your class2. and if someone will say new derived where derived is derived from your class3. and if someone will say delete p, where the actual objects type is derived but the pointer ps type is your class
    5. make destructor virtual if your class has any virtual functions
  10. Why do you need a virtual destructor when someone says delete using a Base ptr thats pointing @ a derived object? - when you say delete p and the class of p has a virtual destructor the destructor that gets invoked is the one assoc with the type of the object*p not necessarily the one assoc with the type of the pointer == GOOD
  11. Different types of polymorphism
    1. types related by inheritance as polymorphic types because we can use many forms of a derived or base type interchangeably
    2. only applies to ref or ptr to types related by inheritance.
    3. Inheritance - lets us define classes that model relationships among types, sharing what is common and specializing only that which is inherently different
    4. derived classes
      1. can use w/o change those operations that dont depend on the specifics of the derived type
      2. redefine those member functions that do depend on its type
      3. derived class may define additional members beyond those it inherits from its base class.
    5. Dynamic Binding - lets us write programs that use objects of any type in an inheritance hierarchy w/o caring about the objects specific types
    6. happens when a virtual function is called through a reference || ptr to a base class
    7. The fact that a reference or ptr might refer to either a base or derived class object is the key to dynamic binding
    8. calls to virtual functions made though a reference/ptr resolved @ runtime
    9. the function that is called is the one defined by the actual type of the object to which ref/ptr refers
  12. How to implement virtual functions in C - keep function pointers in function and use those function ptrs to perform the operation
  13. What are the different type of Storage classes?
    1. automatic storage: stack memory - static storage: for namespace scope objects and local statics
    2. free store: or heap for dynamically allocated objects == design patterns
  14. What is a namespace?
    1. every name defined in a global scope must be unique w/in that scope
    2. name collisions: same name used in our own code or code supplied to us by indie producers == namespace pollution
    3. name clashing - namespace provides controlled mechanism for preventing name collisions
    4. allows us to group a set of global classes/obj/funcs
    5. in order to access variables from outside namespace have to use scope :: operator
    6. using namespace serves to assoc the present nesting level with a certain namespace so that objectand funcs of that namespace can be accessible directly as if they were defined in the global scope
  15. Types of STL containers - containers are objects that store other objects and that has methods for accessing its elements - has iterator - vector
  16. Difference between vector and array - -array: data structure used dto store a group of objects of the same type sequentially in memory - vector: container class from STL - holds objects of various types - resize, shrinks grows as elements added - bugs such as accessing out of bounds of an array are avoided
  17. Write a program that will delete itself after execution. Int main(int argc, char **argv) { remove(argv[0]);return 0;}
  18. What are inline functions?
    1. treated like macro definitions by C++ compiler
    2. meant to be used if there’s a need to repetitively execute a small block if code which is smaller
    3. always evaluates every argument once
    4. defined in header file
    5. avoids function call overload because calling a function is slower than evaluating the equivalent expression
    6. it’s a request to the compiler, the compiler can ignore the request
  19. What is strstream? defines classes that support iostreams, array of char obj
  20. Passing by ptr/val/refArg?
    1. passing by val/refvoid c::f(int arg) – by value arg is a new int existing only in function. Its initial value is copied from i. modifications to arg wont affect the I in the main function
    2. void c::f(const int arg) – by value (i.e. copied) the const keyword means that arg cant be changed, but even if it could it wouldnt affect the I in the main function
    3. void c::f(int& arg) - -by reference, arg is an alias for I. no copying is done. More efficient than methods that use copy. Change in arg == change in I in the calling function
    4. void c::f(const int& arg) - -by reference, int provided in main call cant be changed, read only. Combines safety with efficacy.
    5. void c::f(const int& arg) const – like previous but final const that in addition the function f cant change member variables of cArg passing using pointers
    6. void c::f(int *arg) – by reference changing *arg will change the I in the calling function
    7. void c::f(const int *arg) – by reference but this time the I int in the main function cant be changed – read only
    8. void c::f(int * const arg) – by reference the pointer arg cant be changed but what it points to (namely I of the calling function) can
    9. void c::f(const int * const arg) by reference the pointer arg cant be changed neither can what it points to
  21. Mutable keyword?
    1. keyword is the key to make exceptions to const
    2. mutable data member is allowed to change during a const member function
    3. mutable data member is never const even when it is a member of a const object
    4. a const member function may change a mutable member
  22. Something you can do in C but not in C++? C++ applications generally slower at runtime and compilation - input/output
  23. Difference between calloc and malloc?
    1. malloc: allocate s bytes
    2. calloc: allocate n times s bytes initialized to 0
  24. What will happen if I allocate memory using new & free memory using free? WRONG
  25. Difference between printf and sprintf?
    1. sprintf: a function that puts together a string, output goes to an array of char instead of stdout
    2. printf: prints to stdout
  26. map in STL?
    1. used to store key - value pairs, value retrieved using the key
    2. store data indexed by keys of any type desire instead of integers as with arrays
    3. maps are fast 0(log(n)) insertion and lookup time
    4. std::mapEX:Std::map grade_list //grade_list[“john”] = b
  27. When will we use multiple inheritance?
    1. use it judiciously class
    2. when MI enters the design scope it becomes possible to inherit the same name (function/typedef) from more than one base class == ambiguity
    3. C++ first identifies the function thats the best match for the call
    4. C++ resolves calls to overload before accessibility, therefore the accessibility of Elec_Gadget() checkout is never evaluated because both are good matches == ERROR
    5. resolve ambiguity mp.Borrowable_Item::checkOut(); mp.Elec_Gadget::checkOut(); //error because trying to access private
    6. deadly MI diamond: anytime you have an inheritance hierarchy w/ more than one path between a base class and a derived classEX:FileInput File Output FileIOFile//File and IOFile both have paths through InputFile and OutputFile
  28. Multithreading - C++ does not have a notion of multithreading, no notion of concurrency
  29. Why is the pre-increment operator faster than the post-increment operator? pre is more efficient that post because for post the object must increment itself and then return a temporary containing its old value. True for even built in types
  30. What is a hash and what would you use it for?
  31. What is a dot product and what is a cross product - what would you use them for?
  32. What is 2 ^ 101?

21 Responses to “C++ notes for discussion”

  1. Amit Says:

    Something that can be done in C and not in C++ is Multi-Threading. Because there is no notion of concurrency in C++. In C many threads can run at the same time concurrently.

  2. Mark Says:

    Previous comment about multithreading can be done in C not C++. It’s not correct, multithreading is foreign to both. The languages don’t have the concept.

  3. Anitha Says:

    C and C++ does not support multithreading.

  4. MEwhish Says:

    gud website

    but there are so many other question that arises in our minds,
    please maximize the list of questions and their answer
    also tell me about
    1)macros
    2)storage classes

  5. teja Says:

    array out of bound access is allowed in c and we cant do it in c++

  6. Nilesh Says:

    array out of bound is also allowed in C++, as long as you are in your process address space you can access any memory location.

  7. Ravi Sharma Tata Says:

    we can acess registers from c but not from c++

  8. Trilok Says:

    C and C++ doesn’t support multithreading but they use the multithreading capabilty of the Operating System efficiently.

  9. Aman Mishra Says:

    Regarding efficiency of pre and post increment operators, a temporary is not always needed in case of post? The value of operand can directly used in the next operator evaluation giving a full or partial result. Simple expressions given below, for example, don’t have any difference in execution time:

    1. Pre: x = ++i;
    Post: x = i++;

    2. Pre: x = 5 + ++i;
    Post: x = 5 + i++;

  10. nitin Says:

    Why we can’t overload scopr operator in c++

  11. Madhura Says:

    The members of structure in C++ are public by default. In fact, the only dirrence between a class and struct in C++ is that by default all members are public in struct and private in class.

  12. Lalit from BARC Says:

    We can give support of multithreading in C & C++ both, but the features is not inbuilt in the compiler while if we are talking in term of windows & MFC programming its really v easy to create threads.

  13. Jeff King Says:

    Beside the differences between structure and class discussed about, the other is the different way to initialize them.

  14. Irsal Says:

    Multithreading is an operating system business. If you want C or C++ deal with multithreading, just use win32 function from windows. Other language that can deal with multithreading actually what it does is just wrapping the win32 function with that language.

  15. Madhusudan Says:

    What we can do in C and not in C++.

    main()
    {
    Foo();
    }
    Foo()
    {
    //Do Something
    }

    Compiler will issue warnings (Foo is called before we have defined it). In C++ this cannot be done.

    Another thing we can do is write program in C which use just standard library functions, without actually including the headers.

    main()
    {
    printf(”Hello, World\n”;
    }
    Will compile, warn that printf is undefined, but work like a charm.
    Cannot be done in C++. Have to include stdio.h

  16. bhugz Says:

    answer to question abt wat u can do in C but not in C++ :

    Function protoyping is menatory in C++ but not in C.

    function with no arguments is allowed in C but in not in C++ (at least void in necessary)

    you can have global variable copies defined more than one time in C but in C++ it has to be one and use of extern while accesing that global variable

    use of const

    in C:

    const int i;

    its not allowed in C++ (must be initialized)

  17. Uma Thangaraj Says:

    Q > What can be done in C but not in C++ ?

    A : In C, we can have variable names such as public,private,class etc. which cant be done in C++.
    for eg.

    void main()
    {
    int public;
    public=5;
    printf(”%d”,public);
    }

    The above code is valid in C but not in C++.

  18. suresh Says:

    The members of structure in C++ are public by default. In fact, the only dirrence between a class and struct in C++ is that by default all members are public in struct and private in class

  19. Hari Prasath Says:

    Q:What is meaning of ARP?
    A:ARP Stands for Address Resulation Protocol

  20. Yogesh Says:

    Q:What is meaning of TFTP?
    A:TFTP stands for Trivial File Transfer Protocol.

  21. Hari Prasath Says:

    The members of structure in C++ are public by default. In f

No comments:

如何发掘出更多退休的钱?

如何发掘出更多退休的钱? http://bbs.wenxuecity.com/bbs/tzlc/1328415.html 按照常规的说法,退休的收入必须得有退休前的80%,或者是4% withdrawal rule,而且每年还得要加2-3%对付通胀,这是一个很大...