Question

Provide short answers for the following C++ questions const - data members: - how can you...

Provide short answers for the following C++ questions

const

- data members:

- how can you initialize data members that are const:

- member functions:

- how to declare member functions that operate on a const object:

- why declare them to handle const objects:

inheritance:

- class hierarchy

- order of events when a derived-class object is instantiated and destroyed

-constructor initialization list

0 0
Add a comment Improve this question Transcribed image text
Answer #1

1) Constant Variables or constant data members:

If you make any variable as constant, using const keyword, you cannot change its value. Also, the constant variables must be initialized while declared.

int main
{
 const int i = 10;
 const int j = i+10;  // Works fine
 i++;    // This leads to Compile time error   
}

In this program we have made i as constant, hence if we try to change its value, compile time error is given. Though we can use it for substitution.

2)

A const variable has to be declared within the class, but it cannot be defined in it. We need to define the const variable outside the class.

here t is constant variable decalred in the class, and defining it out side the class as follows.

T1() : t( 100 ){}

Here the assignment t = 100 happens in initializer list, much before the class initilization occurs.

3)

Const class Member function

A const member function never modifies data members in an object.

Syntax :
return_type function_name() const;

Example for const Object and const Member function

class X
{
 int i;
 public:
 X(int x)   // Constructor
 { i=x; }

 int f() const    // Constant function
 { i++; }

 int g()
 { i++; }
};

int main()
{
X obj1(10);          // Non const Object
const X obj2(20);   // Const Object

obj1.f();   // No error
obj2.f();   // No error

cout << obj1.i << obj2.i ;

obj1.g();   // No error
obj2.g();   // Compile time error
}

Output : 10 20

Here, we can see, that const member function never changes data members of class, and it can be used with both const and non-const object. But a const object can't be used with a member function which tries to change its data members.

4)

Types of Inheritance

In C++, we have 5 different types of Inheritance. Namely,

  1. Single Inheritance
  2. Multiple Inheritance
  3. Hierarchical Inheritance
  4. Multilevel Inheritance
  5. Hybrid Inheritance (also known as Virtual Inheritance)

Single Inheritance

In this type of inheritance one derived class inherits from only one base class. It is the most simplest form of Inheritance.

Single Inheritance in C++

Multiple Inheritance

In this type of inheritance a single derived class may inherit from two or more than two base classes.

Multiple Inheritance in C++

Hierarchical Inheritance

In this type of inheritance, multiple derived classes inherits from a single base class.

Hierarchical Inheritance in C++

Multilevel Inheritance

In this type of inheritance the derived class inherits from a class, which in turn inherits from some other class. The Super class for one, is sub class for the other.

Multilevel Inheritance in C++

Hybrid (Virtual) Inheritance

Hybrid Inheritance is combination of Hierarchical and Mutilevel Inheritance.

Hybrid Inheritance in C++

5)

for example consider the following class

class Banana : public MyBase
{
public:
    Banana(void);
    ~Banana(void);
};

The constructor of the derived class gets called after the constructor of the base class. The destructors get called in reversed order.

6)

Understanding the Start of an Object's Lifetime

In C++, whenever an object of a class is created, its constructor is called. But that's not all--its parent class constructor is called, as are the constructors for all objects that belong to the class. By default, the constructors invoked are the default ("no-argument") constructors. Moreover, all of these constructors are called before the class's own constructor is called.



For instance, take the following code:

#include 
class Foo
{
        public:
        Foo() { std::cout << "Foo's constructor" << std::endl; }
};
class Bar : public Foo
{
        public:
        Bar() { std::cout << "Bar's constructor" << std::endl; }
};

int main()
{
        // a lovely elephant ;)
        Bar bar;
}

The object bar is constructed in two stages: first, the Foo constructor is invoked and then the Bar constructor is invoked. The output of the above program will be to indicate that Foo's constructor is called first, followed by Bar's constructor.

Why do this? There are a few reasons. First, each class should need to initialize things that belong to it, not things that belong to other classes. So a child class should hand off the work of constructing the portion of it that belongs to the parent class. Second, the child class may depend on these fields when initializing its own fields; therefore, the constructor needs to be called before the child class's constructor runs. In addition, all of the objects that belong to the class should be initialized so that the constructor can use them if it needs to.

But what if you have a parent class that needs to take arguments to its constructor? This is where initialization lists come into play. An initialization list immediately follows the constructor's signature, separated by a colon:

class Foo : public parent_class
{
        Foo() : parent_class( "arg" ) // sample initialization list
        {
                // you must include a body, even if it's merely empty
        }
};

Note that to call a particular parent class constructor, you just need to use the name of the class (it's as though you're making a function call to the constructor).

For instance, in our above example, if Foo's constructor took an integer as an argument, we could do this:

#include 
class Foo
{
        public:
        Foo( int x ) 
        {
                std::cout << "Foo's constructor " 
                          << "called with " 
                          << x 
                          << std::endl; 
        }
};

class Bar : public Foo
{
        public:
        Bar() : Foo( 10 )  // construct the Foo part of Bar
        { 
                std::cout << "Bar's constructor" << std::endl; 
        }
};

int main()
{
        Bar stool;
}

Using Initialization Lists to Initialize Fields

In addition to letting you pick which constructor of the parent class gets called, the initialization list also lets you specify which constructor gets called for the objects that are fields of the class. For instance, if you have a string inside your class:

class Qux
{
        public:
                Qux() : _foo( "initialize foo to this!" ) { }
                // This is nearly equivalent to 
                // Qux() { _foo = "initialize foo to this!"; }
                // but without the extra call to construct an empty string

        private:
        std::string _foo;
};

Here, the constructor is invoked by giving the name of the object to be constructed rather than the name of the class (as in the case of using initialization lists to call the parent class's constructor).

If you have multiple fields of a class, then the names of the objects being initialized should appear in the order they are declared in the class (and after any parent class constructor call):

class Baz
{
        public:
                Baz() : _foo( "initialize foo first" ), _bar( "then bar" ) { }

        private:
        std::string _foo;
        std::string _bar;
};

Initialization Lists and Scope Issues

If you have a field of your class that is the same name as the argument to your constructor, then the initialization list "does the right thing." For instance,

class Baz
{
        public:
                Baz( std::string foo ) : foo( foo ) { }
        private:
            std::string foo;
};

is roughly equivalent to

class Baz
{
        public:
                Baz( std::string foo )
                {
                    this->foo = foo;
                }
        private:
            std::string foo;
};

That is, the compiler knows which foo belongs to the object, and which foo belongs to the function.

Initialization Lists and Primitive Types

It turns out that initialization lists work to initialize both user-defined types (objects of classes) and primitive types (e.g., int). When the field is a primitive type, giving it an argument is equivalent to assignment. For instance,

class Quux
{
        public:
                Quux() : _my_int( 5 )  // sets _my_int to 5
                { }

        private:
                int _my_int;
};

This behavior allows you to specify templates where the templated type can be either a class or a primitive type (otherwise, you would have to have different ways of handling initializing fields of the templated type for the case of classes and objects).

template 
class my_template
{
        public:
                // works as long as T has a copy constructor
                my_template( T bar ) : _bar( bar ) { }

        private:
                T _bar;
};

Initialization Lists and Const Fields

Using initialization lists to initialize fields is not always necessary (although it is probably more convenient than other approaches). But it is necessary for const fields. If you have a const field, then it can be initialized only once, so it must be initialized in the initialization list.

class const_field
{
        public:
                const_field() : _constant( 1 ) { }
                // this is an error: const_field() { _constant = 1; } 

        private:
                const int _constant;
};

When Else do you Need Initialization Lists?

No Default Constructor

If you have a field that has no default constructor (or a parent class with no default constructor), you must specify which constructor you wish to use.

References

If you have a field that is a reference, you also must initialize it in the initialization list; since references are immutable they can be initialized only once.

Initialization Lists and Exceptions

Since constructors can throw exceptions, it's possible that you might want to be able to handle exceptions that are thrown by constructors invoked as part of the initialization list.

First, you should know that even if you catch the exception, it will get rethrown because it cannot be guaranteed that your object is in a valid state because one of its fields (or parts of its parent class) couldn't be initialized. That said, one reason you'd want to catch an exception here is that there's some kind of translation of error messages that needs to be done.

The syntax for catching an exception in an initialization list is somewhat awkward: the 'try' goes right before the colon, and the catch goes after the body of the function:

class Foo
{
        Foo() try : _str( "text of string" ) 
        { 
        } 
        catch ( ... ) 
        { 
                std::cerr << "Couldn't create _str";
                // now, the exception is rethrown as if we'd written
                // "throw;" here
        }
};
Add a comment
Know the answer?
Add Answer to:
Provide short answers for the following C++ questions const - data members: - how can you...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Please show it in C++. Thank you! Problem Definition Create an inheritance hierarchy containing base class...

    Please show it in C++. Thank you! Problem Definition Create an inheritance hierarchy containing base class Account and derived class Savings-Account. Base class Account should include one data member of type double to represent the account balance. The class should provide a constructor that receives an initial baiance and uses it to initialize the data member. The class should provide three member functions. Member function credit should add an amount to the current balance. Member function debit should withdraw money...

  • In object-oriented programming, the object encapsulates both the data and the functions that operate on the...

    In object-oriented programming, the object encapsulates both the data and the functions that operate on the data. True False Flag this Question Question 101 pts You must declare all data members of a class before you declare member functions. True False Flag this Question Question 111 pts You must use the private access specification for all data members of a class. True False Flag this Question Question 121 pts A private member function is useful for tasks that are internal...

  • C++ program Create a Student class that contains three private data members of stududentID (int), lastName...

    C++ program Create a Student class that contains three private data members of stududentID (int), lastName (string), firstName(string) and a static data member studentCount(int). Create a constructor that will take three parameters of studentID, lastName and firstName, and assign them to the private data member. Then, increase the studentCount in the constructor. Create a static function getStudentCount() that returns the value of studentCount. studentCount is used to track the number of student object has been instantiated. Initialize it to 0...

  • In C++ Create an inheritance hierarchy that a bank might use to represent customers’ bank accounts. All customers at this bank can deposit (i.e., credit) money into their accounts and withdraw (i.e.,...

    In C++ Create an inheritance hierarchy that a bank might use to represent customers’ bank accounts. All customers at this bank can deposit (i.e., credit) money into their accounts and withdraw (i.e., debit) money from their accounts. More specific types of accounts also exist. Savings accounts, for instance, earn interest on the money they hold. Checking accounts, on the other hand, charge a fee per transaction (i.e., credit or debit). Create an inheritance hierarchy containing base class Account and derived...

  • C++ program Create a class Time having data members HH, MM, SS of type integer. Write...

    C++ program Create a class Time having data members HH, MM, SS of type integer. Write a C++ program to do the following: 1. Use a Constructor to initialize HH, MM, SS to 0. 2. Create two Objects of this class and read the values of HH, MM, SS from the user for both objects (Using proper member functions). 3. Use a binary + operator to add these two objects created (Store & display result using separate object). 4. Use...

  • C++ edit: You start with the code given and then modify it so that it does...

    C++ edit: You start with the code given and then modify it so that it does what the following asks for. Create an EmployeeException class whose constructor receives a String that consists of an employee’s ID and pay rate. Modify the Employee class so that it has two more fields, idNum and hourlyWage. The Employee constructor requires values for both fields. Upon construction, throw an EmployeeException if the hourlyWage is less than $6.00 or over $50.00. Write a program that...

  • Write three object-oriented classes to simulate your own kind of team in which a senior member...

    Write three object-oriented classes to simulate your own kind of team in which a senior member type can give orders to a junior member type object, but both senior and junior members are team members. So, there is a general team member type, but also two specific types that inherit from that general type: one senior and one junior. Write a Python object-oriented class definition that is a generic member of your team. For this writeup we call it X....

  • in c++ Define and implement the class Employee with the following requirements: private data members string...

    in c++ Define and implement the class Employee with the following requirements: private data members string type name a. b. double type hourlyRate 2. public member functions a. default constructor that sets the data member name to blank"and hourlyRate to zero b. A constructor with parameters to initialize the private data members c. Set and get methods for all private data members d. A constant method weeklyPay() that receives a parameter representing the number of hours the employee worked per...

  • An array of class objects is similar to an array of some other data type. To...

    An array of class objects is similar to an array of some other data type. To create an array of Points, we write Point parray [4]; To access the object at position i of the array, we write parray [i] and to call a method on that object method, we write parray [i]. methodName (arg1 , arg2 , ...) ; To initialize an array of objects whose values are known at compile time, we can write Point parray [4] =...

  • Please help with this assignment. Thanks. 1. Write a C++ program containing a class Invoice and...

    Please help with this assignment. Thanks. 1. Write a C++ program containing a class Invoice and a driver program called invoiceDriver.cpp. The class Invoice is used in a hardware store to represent an invoice for an item sold at the store. An invoice class should include the following: A part number of type string A part description of type string A quantity of the item being purchased of type int A price per item of type int A class constructor...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT