C++ object-oriented questions

  1. What is a modifier? A modifier, also called a modifying function is a member function that
    changes the value of at least one data member. In other words, an
    operation that modifies the state of an object. Modifiers are also
    known as ‘mutators’. Example: The function mod is a modifier in the
    following code snippet:

    class test
    {
        int x,y;
        public:
        	test()
        	{
           		x=0; y=0;
        	}
    	void mod()
        	{
    	       x=10;
    	       y=15;
        	}
    };
    
  2. What is an accessor? An accessor is a class operation that
    does not modify the state of an object. The accessor functions need to
    be declared as const operations
  3. Differentiate between a template class and class template.
    Template class: A generic definition or a parameterized class not
    instantiated until the client provides the needed information. It’s
    jargon for plain templates. Class template: A class template specifies
    how individual classes can be constructed much like the way a class
    specifies how individual objects can be constructed. It’s jargon for
    plain classes.
  4. When does a name clash occur? A name clash occurs
    when a name is defined in more than one place. For example., two
    different class libraries could give two different classes the same
    name. If you try to use many class libraries at the same time, there is
    a fair chance that you will be unable to compile or link the program
    because of name clashes.
  5. Define namespace. It is a feature in C++ to
    minimize name collisions in the global name space. This namespace
    keyword assigns a distinct name to a library that allows other
    libraries to use the same identifier names without creating any name
    collisions. Furthermore, the compiler uses the namespace signature for
    differentiating the definitions.
  6. What is the use of ‘using’ declaration.
    A using declaration makes it possible to use a name from a namespace without the scope operator.
  7. What is an Iterator class? A class that is used to
    traverse through the objects maintained by a container class. There are
    five categories of iterators: input iterators, output iterators,
    forward iterators, bidirectional iterators, random access. An iterator
    is an entity that gives access to the contents of a container object
    without violating encapsulation constraints. Access to the contents is
    granted on a one-at-a-time basis in order. The order can be storage
    order (as in lists and queues) or some arbitrary order (as in array
    indices) or according to some ordering relation (as in an ordered
    binary tree). The iterator is a construct, which provides an interface
    that, when called, yields either the next element in the container, or
    some value denoting the fact that there are no more elements to
    examine. Iterators hide the details of access to and update of the
    elements of a container class.
    The simplest and safest iterators are those that permit read-only access to the contents of a container class.
  8. List out some of the OODBMS available. GEMSTONE/OPAL
    of Gemstone systems, ONTOS of Ontos, Objectivity of Objectivity Inc,
    Versant of Versant object technology, Object store of Object Design,
    ARDENT of ARDENT software, POET of POET software.
  9. List out some of the object-oriented methodologies. Object Oriented Development (OOD) (Booch 1991,1994), Object
    Oriented Analysis and Design (OOA/D) (Coad and Yourdon 1991), Object
    Modelling Techniques (OMT) (Rumbaugh 1991), Object Oriented Software
    Engineering (Objectory) (Jacobson 1992), Object Oriented Analysis (OOA)
    (Shlaer and Mellor 1992), The Fusion Method (Coleman 1991).
  10. What is an incomplete type? Incomplete types
    refers to pointers in which there is non availability of the
    implementation of the referenced location or it points to some location
    whose value is not available for modification.

    	int *i=0x400  // i points to address 400
    	*i=0;        //set the value of memory location pointed by i.
    

    Incomplete types are otherwise called uninitialized pointers.

  11. What is a dangling pointer?
    A dangling pointer arises when you use the address of an object after
    its lifetime is over. This may occur in situations like returning
    addresses of the automatic variables from a function or using the
    address of the memory block after it is freed. The following
    code snippet shows this:

    class Sample
    {
    public:
            int *ptr;
            Sample(int i)
            {
    	        ptr = new int(i);
            }
    
            ~Sample()
            {
    	        delete ptr;
            }
            void PrintVal()
            {
    	        cout << "The value is " << *ptr;
            }
    };
    
    void SomeFunc(Sample x)
    {
    	cout << "Say i am in someFunc " << endl;
    }
    
    int main()
    {
    	Sample s1 = 10;
    	SomeFunc(s1);
    	s1.PrintVal();
    }
    

    In the above example when PrintVal() function is
    called it is called by the pointer that has been freed by the
    destructor in SomeFunc.

  12. Differentiate between the message and method.
    Message:

    • Objects communicate by sending messages to each other.
    • A message is sent to invoke a method.

    Method

    • Provides response to a message.
    • It is an implementation of an operation.
  13. What is an adaptor class or Wrapper class?
    A class that has no functionality of its own. Its member functions hide
    the use of a third party software component or an object with the
    non-compatible interface or a non-object-oriented implementation.
  14. What is a Null object? It is an object of some
    class whose purpose is to indicate that a real object of that class
    does not exist. One common use for a null object is a return value from
    a member function that is supposed to return an object with some
    specified properties but cannot find such an object.
  15. What is class invariant? A class invariant is a
    condition that defines all valid states for an object. It is a logical
    condition to ensure the correct working of a class. Class invariants
    must hold when an object is created, and they must be preserved under
    all operations of the class. In particular all class invariants are
    both preconditions and post-conditions for all operations or member
    functions of the class.
  16. What do you mean by Stack unwinding? It is a
    process during exception handling when the destructor is called for all
    local objects between the place where the exception was thrown and
    where it is caught.
  17. Define precondition and post-condition to a member function.
    Precondition: A precondition is a condition that must be true on entry
    to a member function. A class is used correctly if preconditions are
    never false. An operation is not responsible for doing anything
    sensible if its precondition fails to hold. For example, the interface
    invariants of stack class say nothing about pushing yet another element
    on a stack that is already full. We say that isful() is a precondition
    of the push operation. Post-condition: A post-condition is a condition
    that must be true on exit from a member function if the precondition
    was valid on entry to that function. A class is implemented correctly
    if post-conditions are never false. For example, after pushing an
    element on the stack, we know that isempty() must necessarily hold.
    This is a post-condition of the push operation.
  18. What are the conditions that have to be met for a condition to be an invariant of the class?
    • The condition should hold at the end of every constructor.
    • The condition should hold at the end of every mutator (non-const) operation.
  19. What are proxy objects? Objects that stand for other objects are called proxy objects or surrogates.
    template <class t="">
    class Array2D
    {
    	public:
            class Array1D
            {
             public:
              T& operator[] (int index);
              const T& operator[] (int index)const;
            };
    
            Array1D operator[] (int index);
            const Array1D operator[] (int index) const;
    };
    

    The following then becomes legal:

    Array2D<float>data(10,20);
    cout<<data[3][6];     //  fine
    

    Here data[3] yields an Array1D object
    and the operator [] invocation on that object yields the float in
    position(3,6) of the original two dimensional array. Clients of the
    Array2D class need not be aware of the presence of the Array1D class.
    Objects of this latter class stand for one-dimensional array objects
    that, conceptually, do not exist for clients of Array2D. Such clients
    program as if they were using real, live, two-dimensional arrays. Each
    Array1D object stands for a one-dimensional array that is absent from a
    conceptual model used by the clients of Array2D. In the above example,
    Array1D is a proxy class. Its instances stand for one-dimensional
    arrays that, conceptually, do not exist.

  20. Name some pure object oriented languages. Smalltalk, Java, Eiffel, Sather.
  21. Name the operators that cannot be overloaded. sizeof, ., .*, .->, ::, ?: Salam in the comments notes that -> can be overloaded.
  22. What is a node class? A node class is a class that,
    • relies on the base class for services and implementation,
    • provides a wider interface to the users than its base class,
    • relies primarily on virtual functions in its public interface
    • depends on all its direct and indirect base class
    • can be understood only in the context of the base class
    • can be used as base for further derivation
    • can be used to create objects.

    A node class is a class that has added new services or functionality beyond the services inherited from its base class.

  23. What is an orthogonal base class?
    If two base classes have no overlapping methods or data they are said
    to be independent of, or orthogonal to each other. Orthogonal in the
    sense means that two classes operate in different dimensions and do not
    interfere with each other in any way. The same derived class may
    inherit such classes with no difficulty.
  24. What is a container class? What are the types of container classes?

    A container class is a class that is used to hold objects in memory or
    external storage. A container class acts as a generic holder. A
    container class has a predefined behavior and a well-known interface. A
    container class is a supporting class whose purpose is to hide the
    topology used for maintaining the list of objects in memory. When a
    container class contains a group of mixed objects, the container is
    called a heterogeneous container; when the container is holding a group
    of objects that are all the same, the container is called a homogeneous
    container.

This entry was posted in C++. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

24 Comments on C++ object-oriented questions

  1. ashish kumar
    Posted 10/11/2004 at 1:42 am | Permalink

    The example that you are giving here is not correct as per my undertstanding.
    Reason. When you call SomeFunc method - you pass and object by value, So a local object is constructed which is bitwise copied from the object that we are passing.
    The destructor called is that of the local one and not the original
    one.
    Please correct it.

    regards
    ashish

    # What is a dangling pointer?
    A dangling pointer arises when you use the address of an object after
    its lifetime is over. This may occur in situations like returning
    addresses of the automatic variables from a function or using the
    address of the memory block after it is freed. The following
    code snippet shows this:

    class Sample
    {
    public:
    int *ptr;
    Sample(int i)
    {
    ptr = new int(i);
    }

    ~Sample() { delete ptr; } void PrintVal() { cout << “The value is ” << *ptr; } };

    void SomeFunc(Sample x) { cout << “Say i am in someFunc ” << endl; }

    int main() { Sample s1 = 10; SomeFunc(s1); s1.PrintVal(); }

    In the above example when PrintVal() function is
    called it is called by the pointer that has been freed by the
    destructor in SomeFunc.

  2. sarada
    Posted 10/12/2004 at 8:06 am | Permalink

    what is the difference between a null and null pointer?

  3. PRAKASH
    Posted 10/20/2004 at 12:22 pm | Permalink

    the questions are good but if had given an option to down load them it would be better.it is very useful

  4. Luther Woodrum
    Posted 10/22/2004 at 8:22 am | Permalink

    In #17, I would think that if a queue isful() that you cannot push another element to it, and after pushing an element onto the stack that isempty() would not be true. You have the conditions reversed.

  5. Umeshkumar
    Posted 11/1/2004 at 10:09 am | Permalink

    This site is very good for acquiring the knowledge on different subjects. Try to provide more questions on every subject.

  6. swapna vellani
    Posted 11/9/2004 at 8:56 am | Permalink

    In #20, Java is mentioned as pure OOL. I don’t think this is true. Because, for a language to be pure object oriented, all the datatypes should be objects and this is not true with the basic datatypes in java(int,char,etc)

  7. Terje
    Posted 11/18/2004 at 2:39 pm | Permalink

    “Differentiate between a template class and class template.
    Template class: A generic definition or a parameterized class not
    instantiated until the client provides the needed information. It’s
    jargon for plain templates. Class template: A class template specifies
    how individual classes can be constructed much like the way a class
    specifies how individual objects can be constructed. It’s jargon for
    plain classes.”

    This is directly in conflict with how these terms are used in the C++ standard: In fact, it’s the other way around: Class templates are templates (as a function templates), and template classes is basically a deprecated expression (almost gone from the 2003 C++ standard), and has been used both as a synonym for class template, and for classes made (instantiated) from templates, hence classes.

    To be interview questions, I think they should at least agree with the standard, and how today’s experts define the terms.

    The point about Java being pure OO has been mentioned, so I won’t reiterate that argument.

    “What is an incomplete type? Incomplete types
    refers to pointers in which there is non availability of the
    implementation of the referenced location or it points to some location
    whose value is not available for modification.

    int *i=0×400 // i points to address 400
    *i=0; //set the value of memory location pointed by i.
    Incomplete types are otherwise called uninitialized pointers.”

    This sounds really confused, and lead to criticism at the comp.lang.c++.moderated newsgroup. An incomplete type is unambiguously a type that hasn’t been completely defined, e.g.:

    class c;

    (”void” is also an incomplete type)

    It has nothing to do with pointers or initialisation.

  8. Jubda
    Posted 11/24/2004 at 3:40 am | Permalink

    Hi Anish,
    Regarding your comment. It is actually an error even if it is passed by value because, the pointer address is copied and not the value and it is destructed. so the address is still there pointing to nothing. Writing a copy contructor that does deep copy will avoid this.

  9. girish
    Posted 12/11/2004 at 8:42 am | Permalink

    why dont we have virtual constructor?require clear answere with some example?

  10. maheshwer
    Posted 12/12/2004 at 9:37 pm | Permalink

    class base
    {
    protected:
    int a;
    public:
    void get()
    {
    cout< <"enter values";
    cin>>a;
    }
    };
    class derived:public base
    {
    int b;
    public:
    void get(int x)
    {
    b=x;
    }
    };
    void main()
    {
    derived ob;
    ob.get();
    ob.get(9);
    }
    in this programm “funtion overloading” can’t possible in single inheritence so solve this problem

  11. Ranjit
    Posted 4/27/2005 at 12:16 am | Permalink

    class base
    {
    private :
    int a;
    public :
    void get()
    {
    cout>a;
    }
    class derived:public base
    {
    public :
    void display()
    {
    cout>i;
    }
    void display()
    {
    cout

  12. Amit
    Posted 6/7/2005 at 7:04 am | Permalink

    Why is sizeof an operator and not a function?

  13. Parvaiah Kale
    Posted 6/16/2005 at 5:35 am | Permalink

    Really this site is very useful for those who wants to prepare for jobs and to understand the the various technologies. I am wondering at the same time if project management questions and software development life cycle questions can be accomodated? any feedback on this?

    Thanks
    Parvaiah

  14. Rucha Neogi
    Posted 8/4/2005 at 1:02 am | Permalink

    1.Which of the following is not true about C++

    A. Code removable
    B. Encapsulation of data and code
    C. Program easy maintenance
    D. Program runs faster

    2 . For the following C program

    struct base {int a,b;
    base();
    int virtual function1();}

    struct derv1:base
    {int b,c,d;
    derv1()
    int virtual function1();}

    struct derv2 : base
    {int a,e;
    }
    base::base()
    {a=2;b=3;
    }
    derv1::derv1()
    {b=5;
    c=10;d=11;}
    base::function1()
    {return(100);
    }
    derv1::function1()
    {
    return(200);
    }

    main()
    base ba;
    derv1 d1,d2;
    printf(”%d %d”,d1.a,d1.b)

    Output of the program is:

    a) a=2;b=3;
    b) a=3; b=2;
    c) a=5; b=10;
    d) none

  15. Robert Hardy
    Posted 8/20/2005 at 5:52 pm | Permalink

    > 1.Which of the following is not true about C++

    > A. Code removable
    > B. Encapsulation of data and code

    > C. Program easy maintenance
    What is this relative to? Programs written in C++ are easy to maintain when compared to programs written in non-OO languages such as C. However compared to Java or C# programs, those written in C++ are difficult to maintain IMO.

    > D. Program runs faster
    Again, what is this relative to? C++ is probably the lowest-level language with OO support. Since it is so low-level it is likely that a program written using C++ will run faster than, for instance, programs written in Java. The speed benefits to be had from C++ would, in a small part, depend on the compiler used. However, the main contributing factor would be the use of polymorphism. Since, unlike other languages such as Java, C++ does not implicitly declare all methods virtual–the programmer is given the choice. This allows the programmer to be selective about how much dynamic binding is introduced into the running program thereby minimising unecessary overhead.

    This page has some good info: http://www.parashift.com/c++-faq-lite/virtual-functions.html

  16. bharath
    Posted 9/23/2006 at 2:34 pm | Permalink

    The technical questions presented on these site are very good and useful but every body giving a chance to comment on very question.I think it will be still better if anybody is there to correct the comments done on the questions so that people who read them will not misunderstand the concepts behind the therotical and programming part

  17. bharath
    Posted 9/23/2006 at 2:40 pm | Permalink

    can any help me to know what do you mean by structure padding

    thanks inadvance

  18. Posted 11/4/2006 at 2:07 pm | Permalink

    Structure padding is something that the compiler does in order to ensure that your data structures are aligned according to the CPU’s requirements. A char can usually be located anywhere in memory, but a 32-bit number is often supposed to be stored on a 32-bit boundary.

    When data is not stored at the preferred alignment, the CPU will either reject it (and throw an exception), or it might continue along, with a performance penalty.

    You can minimize or avoid structure padding issues by grouping members of the same size together. In other words, do not intersperse chars with ints and floats.

    For example, here is a grouping of members that’s going to result in lots of padding:

    char, int, char, float, char, int

    Each ‘int’ or ‘float’ needs to be stored on a 32-bit memory address (depending on your CPU), but in the example above, we keep interspersing ‘char’ members which forces the compiler to ‘pad’ the struct with some additional bytes so that the next int or float can be properly aligned.

    This would be a more optimal arrangement of members:

    int, int, float, char, char, char

    Here, we don’t have the chars mixed in, and the compiler does not have to insert padding to make the int and float members appear at the preferred addresses.

    To test this for yourself, make a struct or class and do a sizeof() on it. The sizes you get will be bigger than you expected when you have lots of mixed up sizes.

    Padding may be unavoidable, but it represents wasted memory.

    Unless it is incompatible in some way, you can minimize padding by promoting some of your chars to shorts, or shorts to ints, or even consider demoting some doubles to floats.

  19. Himmat Jadhav
    Posted 12/25/2006 at 2:38 am | Permalink

    How about initializing reference member of class?

    e.g.
    class sub
    {
    public:
    sub(){}
    ~sub(){}
    };

    class main
    {
    public:
    main(){}
    ~main(){}
    private:
    sub& m_oSub;
    };

    How do I initialize ‘m_oSub’ member of main class, using initialization list is fine but how e.g would be good?

    Thanks in advance,
    -Himmat

  20. Dex
    Posted 1/8/2007 at 1:52 am | Permalink

    Hi,

    why calling virtual Function inside a constructor is not advisable?

    Thanks in advance :)

  21. Sumanta
    Posted 2/26/2007 at 1:24 pm | Permalink

    Can anybody please clarify the difference between automatic and smart pointers?

    What are differences between shared_pointer and scoped_pointers ?

    Thanks in advance:)

  22. Joe
    Posted 10/26/2007 at 8:02 am | Permalink

    Question one is confusing, because the word ‘modifier’ also has another common meaning. In grammar, it can be used to refer to any adjective or adverb that modifies a noun or verb. Some examples of ‘modifiers’ in the C++ language are ‘const’, ’static’ and ‘mutable’.

  23. noch
    Posted 1/9/2008 at 12:49 pm | Permalink

    @Dex - using virtual inside a constructor isnt advisable because when you are using virtual inheritance, the function prefaced with virtual will be run. This may cause for an unwanted creation of an object.

    @Joe - modifier in the C++ tense means that it is a function that modifies the data of a class.

  24. Erich Liu
    Posted 7/2/2008 at 8:02 pm | Permalink

    Q11,
    Let me try to answer the question confusing ashish kumar.

    The sample here does not define a copy constructor in the class,therefore the compiler itself defines one. This will ensure a shallow copy, that means the two objects will share the same memory instead of allocating new memory. After the local variable be freed in the SomeFunc, that will cause dangling pointer of the original object.

    The good way to aviod the problem is to define your own copy constructor, that will ensure a deep copy, just like the following codes.

    Sample::Sample(const Sample &s)
    {
    ptr = new int(*(s.ptr));
    }

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*