Narrowing conversion Problem in Member Initializer in C++ Programming


A narrowing conversion changes a value to a data type that might not be able to hold some of the possible values. Member initializer list is the place where non-default initialization of these objects can be specified. Initializer list is used to initialize data members. The syntax begins with a colon ( : ) .

The program defines a class Base with a private member variable x of type char. The class has a constructor Base(int a) that takes an integer argument and initializes x with the ASCII value of that integer. The constructor also prints the ASCII value of x using the cout statement.

In the main() function, an object o of the Base class is created by passing an integer value of 65 to the constructor. The constructor initializes the value of x with 65 (the ASCII value of 'A') and prints the ASCII value of x which is 65.

Source Code

//Narrowing conversion Problem in Member Initializer
#include<iostream>
using namespace std;
class Base
{
private:
    char x;
public:
    Base(int a):x{a}{
    cout<<"X : "<<(int)x<<endl;
    }
};
 
int main()
{
    Base o(65);
    return 0;
}
 

Output

X : 65
To download raw file Click Here

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples