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

Which is java default access specifier?

There is no such thing as an access specifier in Java. There are access modifiers.

The default access modifier if unspecified is to allow access to classes in the current package only, except within an interface where the default is 'public'

How much a base class members can access of derived class?

Ideally, none. Base classes should have no knowledge whatsoever of their derived classes and therefore should have no access to any members declared in the derived classes. However, derived class methods are accessible via virtual functions declared in the base class. The correct methods (overrides) are called via the virtual table, but the base class itself requires no specific knowledge of the derived class in order to call these methods. This makes sense since a base class cannot know in advance all the classes that may or may not derive from it in the future.

If a method must be guaranteed to be implemented by a derived class, a pure-virtual method can be declared in the base class instead. This renders the base class abstract, meaning you cannot instantiate an object from the base class, only from a derivative that fully implements (or inherits) all the pure-virtual methods.

Conversely, a derived class can access all the public and protected members of its base class.

How do you write a program in C in alphabetical order?

#include<iostream>

#include<list>

struct item

{

item(const char ch):chr(ch), count(1){}

char chr;

size_t count;

};

int main()

{

const size_t size=50;

size_t idx;

std::list<item> freq;

std::list<item>::iterator iter;

std::string test;

for(idx=0; idx<size; ++idx)

test.push_back('a'+rand()%26);

for(idx=0; idx<size; ++idx)

{

for(iter=freq.begin(); iter!=freq.end() && (*iter).chr!=test[idx]; ++iter);

if( iter!=freq.end() )

++(*iter).count;

else

freq.push_back(item(test[idx]));

}

std::cout<<"Frequency table of the string:\n""<<test.c_str()<<""\n"<<std::endl;

for(iter=freq.begin(); iter!=freq.end(); ++iter)

{

item& itm=*iter;

std::cout<<itm.chr<<" = "<<itm.count<<std::endl;

}

std::cout<<std::endl;

}

How can a value from the derived class be assigned to a variable in base class?

Remember that derived classes can access the public and protected members of their base class, but none of the private members. If the member variable in the base class is protected (rather than private), then the derived class can assign it directly. However, this is bad style in OOP as it undermines data-hiding. A protected mutator (set accessor) would be a better option.

How do you create a program to store number in array and to find the avg of the number using c plus plus?

#include

using std::cin;
using std::cout;
using std::endl;

int main()
{
const int numOfElements = 5;//defines how many elements are in your array
double arr[numOfElements] = {0.0};
cout << endl << "Enter " << numOfElements << " for your array";
for (int i = 0; i < numOfElements; i++)
{
cout << endl << (i + 1) << " element: ";
cin >> arr[i];
}

double sum = 0.0;
for (int i = 0; i < numOfElements; i++)
{
sum += arr[i];

}

cout << endl << "Average is: " << (sum/numOfElements) << endl;

system("PAUSE");
return 0;

}

How do you write a program in c plus plus to search a number in an array?

The following function performs a non-recursive linear search of the given vector, returning a constant iterator to the element containing the given value. If the value does not exist, the "one-past-the-end" iterator is returned instead.

std::vector<int>::const_iterator find (int val, const std::vector<int>& v){

for (std::vector<int>::const_iterator it=v.begin(); it!=v.end(); ++it)

if (*it==val) return it;

return v.end();

}

What is the constraint of scope resolution operator?

Wahen we say scope we're referring to the enclosing context of a member. In C++, the scope or context of a member is defined by its enclosing namespace. A namespace allows us to completely separate all the enclosed members from all the members of all other namespaces. Namespaces can also enclose other namespaces. Members that do not have an enclosing namespace of their own are said to exist within the global namespace -- effectively a namespace with no name. However, the global namespace also provides the enclosing context for all other namespaces. That is, namespaces create a hierarchy or "family-tree" where the global namespace serves as the root.

Note that although namespaces are typically created by using the namespace keyword, we also create namespaces whenever we declare a class, struct, union or enum. That is, a class name is a namespace in its own right. If that class is not defined within the context of any other namespace then it implicitly exists within the global namespace.

Namespaces literally allow us to separate names (variable names, function names and class names, etc) into separate "spaces". That is, two namespaces can share the same name provided they exist within separate namespaces. However, it is often necessary for the members of one namespace to refer to the members of another namespace. This is achieved by using the scope resolution operator. If we do not use scope resolution, the compiler will search for the name within the current namespace and if no such name exists, it will search the global namespace. If the name cannot be found in either, a coimpiler error occurs.

With regards to global variables, we do not need to use scope resolution unless the global variable has a name that also exists within the current namespace. But since the global namespace has no name, we simply omit the namespace that would normally preceed the scope resolution operator. For instance, if the global variable were named matrix and the current namespace also happened to contain the same name, we can refer to the global instance as ::matrix.

Of course we could easily avoid such problems by choosing more appropriate names. Variables in the global namespace should always be given the prefix "g_", thus our global matrix becomes g_matrix. By the same token, member variables should be given the prefix "m_", thus our namespace's matrix becomes m_matrix.

While this resolves any potential name-clashes or ambiguity with regards member data and global data, prefixing global functions and member functions in this way would be considered quite unsatisfactory. In these cases scope resolution is the ideal solution.

Of course, it would be better to avoid global data altogether, but that's a different topic entirely.

Do STD have a smell to them?

The one that most commonly causes a foul odor is vaginal trichomoniasis.
mostly bacteria infections- and U T I's

What is role of this pointer?

The this pointer is an implicit, compiler generated pointer to the current object that a method is manipulating. It is used to differentiate scope between parameters and members, in the case where they have the same name. Example...

class myclass {
...
int data1;
...
mymethod(int data1) {
data1 = data1; /*ambiguous */
this->data1 = data1; /* not ambiguous */
}
...
secondmethod(int data2) {
data1 = data2; /* not ambiguous */
}
...
}

Many coders use some prefix, such as underscore, to mark member variables. This works, but is not necessary.

What are input output streams in c plus plus?

The term stream is a generic abstraction that says nothing about the implementation. However, if we use the analogy that gave it its name, a stream of water, we can better understand how a stream works. A water stream allows water to flow from one point to another in one direction only (downstream, with the flow of the current). If we were to throw a stick into the water, it would be carried downstream by the water where it could then be extracted. Sticks can be inserted or extracted automatically by devices, thus allowing information to pass between those devices.

A file stream is a stream that is associated with a device representing a file. If the file is upstream then we can use the stream to extract information from the file. When we extract information from a stream, that stream is known as an input stream; it provides us with information. Conversely, if the file were downstream then we can use the stream to insert information into the file. When we insert information into a stream, that stream is known as an output stream; it carries information away from us.

An input/output stream is one where we can both insert and extract information. An input/output file stream is a typical example: we can extract data from the file associated with the stream, process the data (modify it in some way), and then insert the modified data back into the same file. To implement an input/output stream, we simply use two streams associated with the same device: one specifically for input operations, the other specifically for output operations. This implementation detail is hidden from the user, so the stream appears to be a bi-directional stream as far as the user is concerned.

What is memory leak?

When a piece of software running for an extended time uses more and more memory. The software is not releasing its resources correctly! And so the machine cannot recoup memory.

It is possible that eventually the machine will crash, or the offending software will need restarted.

What are the applications of An Abstract Class in c plus plus?

An abstract class is a class that has a pure virtual function.

A pure virtual function can be used in a base class if the function that is virtualised contains parameters that can and should be interchangeable, but the function should remain intact.

For example, there is a base class Object in a game that will contain movement for simple objects, but the movement function may need to use different parameters per object.

C plus plus supports more object oriented Programming features as compared to JAVA?

No. Java is 100% OOP while C++ supports the concept of primitives (which it inherited from C). Thus C++ supports far more features than Java, but it does not support any more OOP features than Java. Note that there are only four primary OOP features: encapsulation, abstraction, inheritance and polymorphism. Anything beyond that is implementation-specific and outwith the scope of OOP.

How do you inherit from class in c?

struct SClass{

int iNumber;

int (*fpgetValue)();

int (*fpsetValue)();

}Sc;

int m_Func(){

printf("\n\n Hello How are you doing,i called by function pointer");

getchar();

return 1;

}

int _tmain(int argc, _TCHAR* argv[])

{

Sc.fpgetValue=m_Func;

Sc.fpgetValue();

return 0;

}

What are legal variable names and declarations in c and c plus plus?

Any name that is not a reserved word can be a legal variable, function or type name. All names must be alphanumeric, but they cannot begin with a digit. The C++ standard recommends that all user-defined names be written entirely in lower case with underscores for spaces. Some programmers prefer 'camel case' (such as PrintObject and MaxNumber), which was a popular convention amongst the Pascal programming community, however print_object and max_number are the C++ conventions. Names in all caps are typically reserved for macro definitions (which is effectively a separate language from C++ itself), while names with leading underscores should generally be avoided as this convention is utilised extensively within the standard library.

What c plus plus programming statements to implement data abstraction?

Data abstraction is a design concept, whereby interfaces and implementations are kept separate. That is, it should not be necessary to know how an object works in order to use it. The interface provides all you need to know.

This reflects much of real life. When watching TV, you have a remote control which allows you to select a channel, but it is not necessary to know how the TV receives and processes radio signals, nor how it separates one channel from another. Those are implementation details that are only of concern to TV engineers.

In C++, there are no statements as such to implement data abstraction. You achieve it by designing a public interface which is accessible to normal users, and a private interface that is only accessible to the class designer.

How swapping two numbers using pointer in c plus plus?

Starting with a pointer to the pointer to the first element (p1**), verify the first pointer is not null (*p1 != null), retrieve the pointer to the second element (*p2 = *p1.next) and verify it is also not null (*p2 != null), and then retrieve the pointer to the third element (*p3 = *p2.next). Note that *p3 might be null, but *p1 and *p2 must not be null, or the swap can not be performed. Note that using pointer to pointer syntax allows you to treat pointer to first element the same as pointer to subsequent element, i.e. to not need to handle the special case. Also, since you do need to modify the pointer, you need a pointer to the pointer. Set *p1 = *p2, *p3 = *p1, and *p2 = *p3. Note that these assignments must be done using the original values, not the intermediate value, so you will need some temp pointers. The end result is that **p1 will be ordered after **p2.

What is the code in c plus plus for line drawing algorithm using OpenGL?

Here is the C code for DDA line drawing...

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

#include<math.h>

void main()

{

int gd, gm;

float x, y, dx, dy, len;

int x1, y1, x2, y2, i;

detectgraph(&gd, &gm);

initgraph(&gd, &gm,"");

printf("\n Enter the coordinates of line : ");

scanf("%d %d %d %d", &x1, &y1, &x2, &y2);

dx = abs(x2-x1);

dy = abs(y2-y1);

if (dx >= dy) len = dx;

else len = dy;

dx = (x2-x1)/len;

dy = (y2-y1)/len;

x = x1 + 0.5;

y = y1 + 0.5;

i = 1;

while (i <= len)

{

putpixel(x, y, 6);

x = x+dx;

y = y+dy;

i++;

}

getch();

}

-Suraj.

Why is so much attention today focused on object-oriented programing in general and c plus plus in particular?

Actually, there is not that much attention today paid to object-oriented programming. It is not a new technology. It is more than 15 years old, and the design paradigm of object-oriented design and object-oriented programming is relatively well established.

Where the attention today is focused is more on multi-threaded programming. The reason for this is that today's processors are approaching the point where Moore's Law is starting to flatten out, i.e. we are approaching the limits of performance gains in a single processor as technology advances.

Many modern computers solve this problem by having more than one processor. Some have many, even thousands or more, such as in a modern supercomputer. The problem is that it is very difficult to write algorithm's that can adequately take advantage of that parallelism. We tend to think linearly, and our algorithms follow that thinking. Such a linear process, however, can only use one processor at a time. We need to work on algorithms that can utilize all of the available processors in a computer at the same time.

Two "yesterdays" ago, the challenge was Block Structured Programming. One "yesterday" ago, the challenge was Object Orientation. "Today", the challenge is Multi-Threading.

What is stream in C plus plus?

It's a bit difficult to show a class hierarchy using unformatted text alone, so I'll use the scope resolution operator to show the relationships instead.

Note: [] denotes multiple inheritance

ios_base

ios_base::ios

ios_base::ios::istream

ios_base::ios::ostream:

ios_base::ios::istream::ifstream

ios_base::ios::ostream::ofstream

ios_base::ios::[istream/ostream]::iostream

ios_base::ios::[istream/ostream]::iostream::fstream

ios_base::ios::[istream/ostream]::iostream::stdiostream

ios_base::ios::[istream/ostream]::iostream::stringstream

streambuf

streambuf::filebuf

streambuf::stdiobuf

What is a token in c?

Anything that you can't put whitespace between. The indivisible elements of a program.

Example: printf("Sup world %d",variable);

Tokens: (7 total)

printf

(

"Sup World %d"

,

variable

)

;

What do you mean by dynamic initialization of a variable Give an example?

Dynamic initialisation of a variable refers to variables that are initialised at runtime rather than at compile time. Consider the following example:

// return the sum of all numbers in the range [0:n]

const unsigned f (const unsigned n) { return n<=1?n:n+f(n-1); } // recursive!

int main (void) {

unsigned x {f (42)}; // dynamic initialisation

// ...

}

Here, x has to be dynamically initialised (at runtime) because the return value of f () cannot be determined at compile time.

The function f() has a linear time complexity (O(n) in big-O notation) however we can improve the execution time by removing all the recursions and reducing the function to a much simpler constant-time calculation:

// return the sum of all numbers in the range [0:n]

const unsigned f (const unsigned n) { return (n+1)*n/2; }

While this will greatly reduce the runtime cost, we still incur dynamic initialisation, albeit in constant time (O(1) as opposed to O(n)). Ideally we want to eliminate dynamic initialisations wherever possible.

Note that in the original call, we passed the constant value 42. Constant expressions such as this are extremely useful because they allow us to perform compile-time computation and thus avoid (some) dynamic initialisation. We can take advantage of this by declaring the function constexpr rather than just const:

// return the sum of all numbers in the range [0:num]

constexpr unsigned f (const unsigned n) { return (n+1)*n/2; }

int main (void) {

unsigned x {f (42)}; // static initialisation

// ...

}

Through compile-time computation, the example is now functionally equivalent to:

int main (void) {

unsigned x {903}; // static initialisation

// ... }

In other words, the function call is eliminated completely so we incur no runtime cost at all. The value 903 is the return value of f (42). Just as importantly, if we subsequently called the function with a variable expression, the compiler will generate a function call which will be invoked at runtime. Thus we get the best of both worlds: compile-time computation when possible and constant-time dynamic initialisation if (and only if) it is needed.