answersLogoWhite

0

📱

C++ Programming

Questions related to the C++ Computer Programming Language. This ranges all the way from K&R C to the most recent ANSI incarnations of C++, including advanced topics such as Object Oriented Design and Programming, Standard Template Library, and Exceptions. C++ has become one of the most popular languages today, and has been used to write all sort of things for nearly all of the modern operating systems and applications." It it a good compromise between speed, advanced power, and complexity.

2,546 Questions

How do you do image cropping in visual c plus plus 6?

Use a bitmap view control setting the width and height to the size of the cropped image. Then move the image within this window so the portion you wish to see is centred in the view. For example, suppose you have a 50x48 pixel image and you want to crop to 48x48. In other words you want to remove two columns of pixels from the left side, or one column from each side, or two from the right side. Start by creating a view of the required size (48x48). Then load the bitmap and set the left coordinate to either -2, -1 or 0, relative to the view.

Is there any difference in allocation of the memory of the member of class and object?

A class is the definition of a type -- it consumes no memory in an off itself. An object is an instance of a class, and therefore consumes memory, equal to the total size of all its member variables (attributes), including base class members, plus padding for alignment. If the class declares any virtual methods, a v-table is also created, which consumes additional memory.

What is the difference between destructors in c plus plus and c sharp?

In C# only class instances can have a destructor, whereas both class and struct instances can have a destructor in C++. While syntactically similar, a C++ destructor executes exactly as written, whereas a C# destructor merely provides the body of the try clause of the class' finalize method.

What is encapsulate?

Wrenn first referred to cultural encapsulation in his 1962 work, The Culturally Encapsulated Counselor. His term is cited in numerous current works referring to culturally competent counseling. Cultural encapsulation is the process of working with clients from an ethnocentric perspective, where one does not effectively understand the world view and culture of origin of the client, nor do they integrate this knowledge into the counseling process. Thus, cultural encapsulation is problematic in therapy and can negatively impact the therapeutic alliance.

Explain the passing parameters as function in Call by Value and Call by Reference and then distinguish between them?

Call by value essentially passes a copy of an object's value whereas call by reference essentially passes the object itself. Pass by reference is the preferred method whenever possible as call by value will automatically invoke the object's copy constructor, which is often unnecessary, especially if the object is not affected by the function call (pass by constant reference).

How do you print characters up and down in c plus plus vs. side to side?

Place a newline (linefeed) character ('\n') after each character you print.

Depending on the device you may need a carriage return as well ('\r'). Usually the carriage return comes before the linefeed, but can often be treated as a string of two characters ("\r\n").

Write a program to find a substring in a given string in c?

#include<stdio.h>

#include<conio.h>

int main()

{

int i=0,j=0,k=0,count=0,l=0,k1=0;

char a[80],b[80];

clrscr();

printf("\nEnter main string:-\n");

gets(a);

printf("\nEnter sub-string:-\n");

gets(b);

l=strlen(b);

while (a[i]!=EOF)

{

if (a[i]==b[j])

{

i++;

j++;

k1=1;

if (j==l)

{

j=0;

k=1;

count=count+1;

}

}

else

{

if (k1==1)

{

j=0;

k1=0;

}

else

i++;

}

}

if (k==1)

{

printf("\n\nThe given sub-string is present in the main string.");

printf("\nIt is present %d times.",count);

}

else

{

if (k==0)

printf("\n\nThe given sub-string is not present in the main string.");

}

}

What is searching in c plus plus language?

Searching in C++ is the same as searching in any language. It is the process of locating a subset of data within a data set, whether to determine if the subset exists or does not exist in the set. The set of data is typically a set of objects contained in an array, a list, a vector, or some other container object that can be iterated one element at a time, while the subset is typically a single object which may or may not exist in the set of objects. In other words, you must search for a specific value in order to ascertain if that value exists in the set.

All search algorithms have a time complexity which can be expressed using big-O notation. The best case is O(1), meaning constant time. That is, the time taken to search for any value in the set is exactly the same, regardless of the value's position in the set. Unfortunately, this is impossible as O(1) can only be guaranteed when the value being sought happens to be the first value in the set or the set only has one value. The worst case is O(n) for a set of n elements, where every value in the set must be inspected. This can occur when the value being sought does not exist or is the final element in the set.

The structure that contains the data can have a large effect on time complexity. For instance, with a linear structure, such as an array, the average time complexity is O(n/2) if the array is in sorted order. However, this can be reduced to O(log n) by starting the search in the middle of the structure rather than at the beginning. If the middle value is greater than the value being sought, you can eliminate all the elements to the right of that value. If it is less, you can eliminate all the values to the right. You then repeat the process using the remaining elements, essentially halving the amount of data to be searched at each stage until there is only one element left to inspect. If it is not the value you are looking for, the value does not exist in the set.

How do you read a word with blank space in c plus plus?

A word with blank spaces is not a word, it is a collection of words, possibly a sentence, a paragraph or an entire book. These are strings (character arrays) and you can read these just as easily as you can an individual value, using the std::getline() function. The following example demonstrates this.

#include<iostream>

#include<sstream>

int main()

{

std::string s;

std::cout<<"Type some words: ";

std::getline( std::cin, s );

std::cout<<"You typed:"<<s.c_str()<<std::endl;

}

What is base class pointer?

It is exactly what it says it is: a pointer to a base class. The assumption is that you have an object to a derived class, but actually hold a pointer to its base class. The following minimal example demonstrates this:

class base{ public: virtual ~base(){} };

class derived: public base{};

int main()

{

base* p = new derived; // base class pointer to a derived instance.

delete( p );

return(0);

}

Note that derived has an "is-a" relationship with base (derived is a base), thus the above code is perfectly legal. Moreover, because the base class destructor is declared virtual, when you delete p you automatically destroy the instance of derived before the instance of base, thus ensuring a clean teardown (without a virtual destructor, a dangling reference to derived would be left behind, which will only lead to problems further down the line).

Taking things further, calling any virtual methods upon the base class automatically invokes the override in your derived class, thus ensuring that your derived class behaves accordingly, polymorphically, even though you only hold a pointer to the base class. In other words, the base class provides a generic interface that is common to all its derivatives, and you can call those generic methods via the base class pointer without ever needing to know the actual derived type.

Remember that base classes should never know anything about their derivatives since a new derivative could be created at any time in the future and would therefore be impossible to predict in advance. But so long as the derivative makes use of the virtual functions (the generic interface) provided by the base class, there is never any need to know the actual type. The derivative's own v-table takes care of that for you, thus completely eliminating the need for expensive runtime type information and dynamic downcasts (which is always a sign of poor class design). This then makes it possible for your derived class overrides to call non-generic methods, thus extorting non-generic behaviour from what is essentially a generic, base class pointer.

Explain about exception handling with multiple exception?

Exception handling in Java is done through a try-catch-finally block. The "try" block of code is where you put the code which may throw an exception. The "catch" block of code is where you put the code which will execute after an exception is thrown in the try block. This is often used to display an error message, or to mitigate problems caused by the exception. The "finally" block is where you put code that you want to execute after the try and catch blocks have been processed.

// example code for catching exception while reading from a file

try {

// this line of code can throw a FileNotFoundException

FileReader in = new FileReader("myfile.txt");

// this line of code can throw an IOException

in.read();

} catch(FileNotFoundException ex) { // catch first exception type

System.err.println("Cannot find myfile.txt!");

} catch(IOException ex) { //catch second exception type

System.err.println("Cannot read from myfile.txt!");

} finally { // no matter what we want to close the file, so do it here

// however, this line can also cause an exception, so we need to catch that, too

try {

in.close();

catch(IOException ex) {

// not much we can do about an exception that occurs here

}

}

Why you have to declare variable first in turbo c?

All variables (and constants) must be declared before they can be used. This is so the compiler knows exactly how much memory to allocate to the variable, as the declaration tells the compiler exactly what the variable's type is.

What is an infinite loop in c plus plus?

An infinite loop is one sequence of commands that just repeats over and over again forever. When it comes to creating an infinite loop you can use the:

for

do while

and do statements.

using the keywords 'true'

What is pure object oriented language?

Object-oriented (OO) applications can be written in either conventional languages or OOPLs, but they are much easier to write in languages especially designed for OO programming. OO language experts divide OOPLs into two categories, hybrid languages and pure OO languages. Hybrid languages are based on some non-OO model that has been enhanced with OO concepts. C++ (a superset of C), Ada 95, and CLOS (an object-enhanced version of LISP) are hybrid languages. Pure OO languages are based entirely on OO principles; Smalltalk, Eiffel, Java, and Simula are pure OO languages.

Reference: Tokar, Joyce L. "Ada 95: The Language for the 90's and Beyond."

" According to me JAVA is not a pure oop Language ,because java contains primitive datatypes that's not an Objects."

  • Smalltalk
  • Eiffel
  • java

a programming language that includes all the oops concepts i,e object, class , inheritance,abstraction, encapsulation, data binding, and message passing is called a completely object oriented programming..

example:java.

How to write an algorithm that reads a number N calculates and displays the reverse of N e.g 3465789 becomes 9875643?

Iteratively divide N by 10, recording the remainder of the division at each step, until N has value of zero. Then interatively recall the remainders, in the same order they were retrieved, and write them from left to right.

What is the declaration of overloaded pre-increment operator implemented as member function?

The pre-increment operator accepts no parameters and returns the same object (by reference) after incrementing.

The post-increment operator accepts an unused (dummy) integer parameter and returns a copy of the object (by value) that is made immediately prior to incrementing the object.

Note that it is good practice to always use the pre-increment operator even if a post-increment operator exists. The only time you should ever use a post-increment is when you actually store the return value. If you don't store the return value then you will end up making an unnecessary copy, which is highly inefficient. With primitive data types that are less than or equal in length to a pointer this isn't a major issue, but it's good practice nonetheless. If you do it for primitives then you're far more likely to remember to do it for class instances as well.

The following example emulates an integer type with pre-increment and post-increment operators implemented:

class Simple

{

public: // Construction:

Simple(int data = 0):m_data(data){}

Simple(const Simple& simple):m_data(simple.m_data){}

public:

// Assignment:

Simple& operator= (const Simple& simple) {

m_data = simple.m_data;

return( *this ); }

// pre-increment:

Simple& operator++ () { // no parameters!

++m_data; // increment this object

return( *this ); } // return a reference to this object

// post-increment:

Simple operator++(int) { // int parameter (not used)!

Simple copy( *this ); // call the copy constructor

++m_data; // increment this object

return( copy ); } // return the copy (by value)

private:

int m_data;

};

How do you programme 1 232 34543 232 1 in C?

int main (void)

{

puts ("1 232 34543 232 1");

return 0;

} int main (void)
{ puts ("1 232 34543 232 1"); return 0; }

When is a function executed and where should a function prototype and function definition appear in a source program?

If you want to use prototype it has to be declared before main(). If you have a function of type double with one argument of type int (with name arg), and the function name is func, then we have:

#include

...

double func(int arg);

...

int main(...)

{

...

return 0;

}

...

double func(int arg)

{

...

}

What is file mode and list various file mode operations available?

A file mode describes how a file is to be used, to read, to write to append etc. When you associate a stream with a file, either by initializing a file stream object with a file name or by using open() method, you can provide a second argument specifying the file mode.

e.g. stream_object.open("filename",filemode);

Following is the list of filemodes available in C++

ios::in

ios::out

ios::binary

ios::ate

ios::app

ios::trunc

ios::nocreate

ios::noreplace

What is the function and purpose of cinema?

I've written a Blog about the same topic in relation to some events in my country: http://srijanfoundation.wordpress.com/2007/11/02/chak-de-india-the-non-message/.

Love,

Rahul Dewan

--

http://srijanfoundation.wordpress.com/

http://srijantech.wordpress.com/

http://www.srijan.in

Which function reads character into an array specified bt its parameter in c plus plus?

void foo (char& c)

{

cin >> c;

}

int main()

{

char ch[10] {};

for (size_t c=0; c!=10; ++c)

foo (c[0]);

}

What is the difference between structures and class?

HedgingI have removed all but one answer while writing this. Please check my references to the c++ standard before removing this as vandalism; nearly every info bit on this page was incorrect or misunderstood to begin with. BackgroundThe question here regards specifically c++. This is not a cross-language question; neither struct nor class means the same thing from language to language, and c++ is the only language which has both in a way such that they are related (as well as its offshoots, such as concurrent c++.) This question is a common misunderstanding, though, for novice c++ programmers, and is frequently given in c++ faqs. Outside of c++, the answer is "those terms could mean anything." Primary answerThe fundamental issue is that of maintaining backwards compatability with C. When Bjarne created C++ (under the old name C with Classes) he wanted to emulate Smalltalk's object model in C. One of the important features Bjarne was adding to C++ was the concept of accessor privelege (private, public and protected.) When those things are added to a language, it is generally done such that private is the default.

In order for code from C to work with C++, the members of a structure would be expected to be public. However, Bjarne knew that default privacy was important. The solution chosen was to clone the "struct" keyword and make this one small change. In fact structs and classes are the same thing; you can inherit structs from classes and vice versa (though it's pretty stupid, it's legal.) The ONLY technical difference between structs and classes is whether members default to private or public accessorship. This can be derived from the language of section 3.1 of the C++ standard (ISO IEC 14882-1998.)

Repeat with me: "The only difference in C++ between struct and class is that struct is default public, whereas class is default private."

Extra informationSeveral misunderstandings were in place here. I will explain them one by one, so that their removal is not protested. Value and Reference Typing"''structures are value typed where as classes are refernce typed''"'''Incorrect'''. This was the case in Microsoft Visual C++ 5 and 6. The problem is that MSVC5 and 6 are older than C++; they implemented speculative versions of the language before the standard came out. Both have quite a few errors which were good guesses but didn't pan out; this is one of them. An easier example is:

for (int i=0; i<10; ++i) {} int i;

The compiler will incorrectly flag that as a redeclaration and fail.

Inheritance"''Class can be inherited But Structure can't be inherited''"'''False''', and easily tested.

#include

struct base {

public: virtual int foo() { return 5; }

};

struct child {

public: int foo() { return 9; }

};

int main() { base* example = new child; std::cout << child.foo(); }

Initialization"''In structures we cannot initilase the variable during the declaration while in classes we can.''"'''False'''. You may tuple initialize any structure or class which is pure POD, and you may not tuple initialize any structure or class which contains methods. However, you may initialize structures or classes with methods in their constructor instead. Anonymous Classes and Anonymous Structures"''Structure can be declared without a tag at the first time, but not in case of class.''"'''Wrong'''. The fault is in the example code. Old code:

struct { int something; } sFoo;

sFoo sfoo; // works fine

class { int something; } cFoo;

cFoo cfoo; // error: cannot instantiate

The problem is not about classes and structures; it's about default publicity. Structures are default public and classes are default private. When declared in that fashion, since there is no explicit constructor, a constructor is generated by the compiler for each. The constructor for the structure is default public, so the structure constructs just fine. However, the constructor for the class is default private, meaning that at instantiation time, the programmer does not have the access privelege to construct it. The error that results in most compilers talks about being unable to instantiate the class, and that can easily be misunderstood as a code bug, when in fact it's a usage bug.

Polymorphism"''Structure s does not support polymorphism while class does.''"Simply '''false''', and a common and often repeated misunderstanding. The test for inheritance above also happens to display polymorphism. POD versus UDT"''A structure is an entity that is defined in terms of other structures or primitive datatypes. As a result, a structure is normally considered to be a complex-, or compound datatype. With structures the default access type is public. Classes are similar to structures in that they are made up of other datatypes, but they differ in one significant respect - classes contain information on the program functions (formally termed "methods") that will be used to manipulate the data that the class can store. The default access type for classes is private.''"'''This is a more complex issue'''. Whereas this is generally the case in code, that's by convention; the language makes no such requirement. In fact the author of this comment even tips his hat to that structures may have methods later, but the phrasing here suggests that this is part of c++, whereas in fact it is not. More clearly put, there is the concept of a "POD type." POD, or Plain Old Data, is any type which consists solely of inert storage - pointers, integers, arrays, that sort of thing. The alternative is called a UDT, or user-defined type; whereas most POD is user defined and whereas most POD is typal, what a user-defined type is meant to mean is a type which has user-defined behavior, ie something other than what the hardware does. Good examples are arithmetic number classes (a class which stores a numerator and a denominator, instead of the real value, so that there is no loss of precision) and many instances of the C++ string class, which frequently implement such things as shared buffers and lazy copies. The fundamental issue here is that most C++ programmers use the struct keyword to make POD and the class keyword to make everything else, and the behavior is so common that it's important to know it; however it's also important to realize that that's an idiom, not a language requirement, because sometimes POD should have methods like copy constructors, such as when copying the data requires things that aren't usually handled, like copying a word at a time over a limited-range bus. AnswerIn structure,the default access specifier is public,where in class the default access specifier is private.